Need a complete Sitemap solution? Check out Nuxt Simple Sitemap, it integrates with Nuxt Content's document-driven mode and frontmatter.
Otherwise, feel free to implement your own with the below guide.
This can be created by utilising the sitemap library, which can be installed as follows:
pnpm add sitemap
We will be utilising the server routes available within Nuxt, and to do so you'll need to create the server/ directory within your website's root directly.
Once this is done, create a routes/ directory inside this, and add a sitemap.xml.ts file, this will translate to /sitemap.xml.
You'll need to add the following:
import { serverQueryContent } from '#content/server'
import { SitemapStream, streamToPromise } from 'sitemap'
export default defineEventHandler(async (event) => {
// Fetch all documents
const docs = await serverQueryContent(event).find()
const sitemap = new SitemapStream({
hostname: 'https://example.com'
})
for (const doc of docs) {
sitemap.write({
url: doc._path,
changefreq: 'monthly'
})
}
sitemap.end()
return streamToPromise(sitemap)
})
Now, once users go to https://example.com/sitemap.xml, you'll find the generated XML file with all your pages.
When using nuxt generate, you may want to pre-render the sitemap since the server route won't be able to run on a static hosting.
You can do this using the nitro.prerender option in your nuxt.config:
export default defineNuxtConfig({
// ...
nitro: {
prerender: {
routes: ['/sitemap.xml']
}
}
})
[
{
"title": "Transformers",
"path": "/content-v2/recipes/transformers",
"stem": "content-v2/6.recipes/2.transformers",
"description": "Transformers are responsible for parsing and manipulating contents in Nuxt Content."
},
{
"title": "Introduction",
"path": "/content-v2/v1/getting-started/introduction",
"stem": "content-v2/7.v1/1.getting-started/1.introduction",
"description": "Empower your NuxtJS application with the @nuxt/content module: write in a content/ directory and fetch your Markdown, JSON, YAML and CSV files through a MongoDB-like API, acting as a Git-based Headless CMS."
}
]