In this chapter we will describe how to implement a sitemap.
In Nuxt 3 you can define custom server routes under the ~/server/routes
directory. Everything you put there will be available under your-url.com/FILENAME
If you look inside you will find our example implementation for how a sitemap can be implemented.
The code is pretty straight forward. First we fetch the navigation data from the navigation service through the Content API. Since this route is defined on the server side, we require the RemoteAPI
from the Content API. To instantiate the API it is possible to use the createRemoteApi()
from the utils package.
Next we map all seo routes from the navigation data to an xml string and set the response header to Content-Type=text/xml
. That’s basically it. If you want, you can also provide a custom stylesheet for your xml or extend the sitemap with custom route entries.
// ~/server/routes/sitemap.xml.ts
import { createRemoteApi } from '~/utils/fsxa'
export default defineEventHandler(async (event) => {
const remoteApi = createRemoteApi(useRuntimeConfig(), useAppConfig())
const baseURL = getRequestURL(event).origin
const navigationData = await remoteApi.fetchNavigation({ locale: 'de_DE' })
const seoRoutes = Object.keys(navigationData?.seoRouteMap || [])
const xmlString = `<?xml version="1.0" encoding="UTF-8"?>
<urlset>
${seoRoutes
.map((seoRoute) => `<url><loc>${baseURL}${seoRoute}</loc></url>`)
.join('\n')}
</urlset>`
setResponseHeader(event, 'Content-Type', 'text/xml')
return xmlString
})