Dynamic URL Endpoint
Use runtime API endpoints to generate dynamic URLs for your sitemap.
Nuxt SEO Pro
- Nuxt Redirects
- Nuxt Google Search Console
- Nuxt Internal Links
- Nuxt SEO Analyze
Save $170 on the presale now.
Introduction
In some instances, like using a CMS, you may need to implement an endpoint to make all of your site URLs visible to the module.
To do this, you can provide user sources to the module.
Dynamic URLs from an external API
Fetching from an external API
When you have a source that is a third-party API returning dynamic URLs,then you have a couple of options.
- Add the endpoint directly to the
sources
config - Good for endpoints that return the data already in the correct format - Make an API endpoint that returns the URLs - Required when you have to transform the data or implement your own caching
1. Using sources config
If the URL you're fetching from requires any extra headers to work, you can provide a source as an array, where the second option is the fetch options.
nuxt.config.ts
export default defineNuxtConfig({
sitemap: {
sources: [
// fetch from an unauthenticated endpoint
'https://api.example.com/pages/urls',
// fetch from an authenticated endpoint
[
'https://authenticated-api.example.com/pages/urls',
{ headers: { Authorization: 'Bearer <token>' } } // fetch options
]
]
}
})
2. Create your own endpoint
- Create a new API endpoint
In this code snippet we're using the defineSitemapEventHandler
helper to create a new API endpoint.
This is a simple wrapper for defineEventHandler
that forces the TypeScript types.
import { defineSitemapEventHandler } from '#imports'
import type { SitemapUrlInput } from '#sitemap/types'
// server/api/__sitemap__/urls.ts
export default defineSitemapEventHandler(() => {
return [
{
loc: '/about-us',
// will end up in the pages sitemap
_sitemap: 'pages',
},
] satisfies SitemapUrlInput[]
})
import { defineSitemapEventHandler } from '#imports'
import type { SitemapUrl } from '#sitemap/types'
export default defineSitemapEventHandler(async () => {
const [
posts,
pages,
] = await Promise.all([
$fetch<{ path: string }[]>('https://api.example.com/posts')
.then(posts => posts.map(p => ({
loc: p.path,
// make sure the post ends up in the posts sitemap
_sitemap: 'posts',
} satisfies SitemapUrl))),
$fetch<{ path: string }[]>('https://api.example.com/pages')
.then(posts => posts.map(p => ({
loc: p.path,
// make sure the post ends up in the posts sitemap
_sitemap: 'pages',
} satisfies SitemapUrl))),
])
return [...posts, ...pages]
})
Having issues with the defineSitemapEventHandler
types? Make sure you have a server/tsconfig.json
!
- Add the endpoint to your
nuxt.config.ts
export default defineNuxtConfig({
sitemap: {
sources: [
'/api/__sitemap__/urls',
]
}
})
export default defineNuxtConfig({
sitemap: {
sitemaps: {
posts: {
sources: [
'/api/__sitemap__/urls/posts',
]
}
}
}
})
Did this page help you?