
Generate a sitemap using the Nuxt 3 Content module
If you're using Nuxt 3 and looking to generate a sitemap for your site, you may have run into some challenges finding a solution that works. I recently encountered this issue myself and spent some time searching for a solution that would work with Nuxt 3 and the Nuxt Content module. After some trial and error, I finally found a solution that worked for me and I want to share it with you in this blog post. Additionally, I want to document it for my own reference in case I need to generate a sitemap for a Nuxt 3 site again in the future.
I tested with a fork of the @nuxt/content moduele, but the technique should also work for the original module. I'm using the fork because it has some additional features that I needed for my site. You can find the fork here: https://github.com/funkenstudio/sitemap-module-nuxt-3/tree/experimental
In nuxt.config.ts
, I added the following sitemap configuration:
import blogRoutes from './helpers/blogRoutes'
// ...
sitemap: {
hostname: 'http://localhost',
cacheTime: 1000 * 60 * 15,
routes: blogRoutes,
defaults: {
changefreq: 'weekly',
priority: 1,
lastmod: new Date().toISOString()
},
},
In helpers/blogRoutes.js
I added the following code to request my constructed API route:
/**
* We can't use imports here, so instead we just fetch
* our routes from an API endpoint that can use import.
*/
export default async () => {
return await $fetch('/api/blog_routes', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
})
}
And finally in api/blog_routes.js
I used serverQueryContent
to fetch all of my blog posts and then return an array
of routes for the sitemap:
import { eventHandler } from 'h3'
import { serverQueryContent } from '#content/server'
export default eventHandler(async event => {
const { req, res } = event
if (req.method !== 'POST') {
res.statusCode = 405
res.end()
return
}
// const config = useRuntimeConfig()
const docs = await serverQueryContent(event).find()
return docs.map(item => {
return { url: item._path }
})
})