Guides

Dynamic URL Endpoints

Last updated by
Harlan Wilton
in doc: wordpress example.

Introduction

When working with a CMS or external data sources, you may need to generate sitemap URLs dynamically at runtime.

The module supports two types of data sources:

  • JSON responses from API endpoints
  • XML sitemaps from external sources

Using External XML Sitemaps

If you have an existing XML sitemap, you can reference it directly in your configuration:

nuxt.config.ts
export default defineNuxtConfig({
  sitemap: {
    sources: [
      'https://example.com/sitemap.xml',
    ]
  }
})

Dynamic URLs from External APIs

When fetching dynamic URLs from external APIs, you have two main approaches:

  1. Direct source configuration - Use when the API returns data in the correct format
  2. Custom API endpoint - Use when you need to transform data or implement caching

1. Using Source Configuration

For APIs that require authentication or custom headers, provide sources as an array with fetch options:

nuxt.config.ts
export default defineNuxtConfig({
  sitemap: {
    sources: [
      // Unauthenticated endpoint
      'https://api.example.com/pages/urls',
      // Authenticated endpoint
      [
        'https://authenticated-api.example.com/pages/urls',
        { headers: { Authorization: 'Bearer <token>' } }
      ]
    ]
  }
})

2. Creating Custom Endpoints

Step 1: Create the API endpoint

Use the defineSitemapEventHandler helper to create type-safe sitemap endpoints:

// server/api/__sitemap__/urls.ts
import { defineSitemapEventHandler } from '#imports'
import type { SitemapUrlInput } from '#sitemap/types'

export default defineSitemapEventHandler(() => {
  return [
    {
      loc: '/about-us',
      // Specify which sitemap this URL belongs to
      _sitemap: 'pages',
    },
  ] satisfies SitemapUrlInput[]
})
Ensure you have a server/tsconfig.json file for proper TypeScript type support.

Step 2: Configure the endpoint

Add your custom endpoint to the sitemap configuration:

export default defineNuxtConfig({
  sitemap: {
    sources: [
      '/api/__sitemap__/urls',
    ]
  }
})
Did this page help you?