### Install @nuxtjs/sitemap Source: https://github.com/nuxt-modules/sitemap/blob/main/README.md Install the @nuxtjs/sitemap dependency to your Nuxt project using the Nuxt CLI. ```bash npx nuxi@latest module add sitemap ``` -------------------------------- ### Install Nuxt Sitemap Module Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/0.getting-started/1.installation.md Install the @nuxtjs/sitemap package using npm or yarn. This is the first step to integrating sitemap generation into your Nuxt.js application. ```bash npm install @nuxtjs/sitemap # or yarn add @nuxtjs/sitemap ``` -------------------------------- ### E-commerce Site Example Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/3.chunking-sources.md Example configuration for an e-commerce site, setting a default chunk size and specific chunk sizes for different sitemaps. ```typescript export default defineNuxtConfig({ sitemap: { defaultSitemapsChunkSize: 10000, sitemaps: { products: { sources: ['/api/products/all'], chunks: 2000, }, categories: { sources: ['/api/categories'], chunks: true, // Uses default 10k } } } }) ``` -------------------------------- ### Zero Runtime Mode Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/2.performance.md Example of enabling `zeroRuntime` to generate sitemaps at build time. ```typescript export default defineNuxtConfig({ sitemap: { zeroRuntime: true } }) ``` -------------------------------- ### Configure Sitemap with Videos Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/1.images-videos.md Example of configuring sitemap entries with video data in Nuxt. This demonstrates how to add comprehensive video metadata to a sitemap location. ```typescript export default defineNuxtConfig({ sitemap: { urls: [ { loc: '/blog/my-post', videos: [ { title: 'My video title', thumbnail_loc: 'https://example.com/video.jpg', description: 'My video description', content_loc: 'https://example.com/video.mp4', player_loc: 'https://example.com/video.mp4', duration: 600, expiration_date: '2021-01-01', rating: 4.2, view_count: 1000, publication_date: '2021-01-01', family_friendly: true, restriction: { relationship: 'allow', restriction: 'US CA', }, platform: { relationship: 'allow', platform: 'web', }, price: [ { price: 1.99, currency: 'USD', type: 'rent', } ], requires_subscription: true, uploader: { uploader: 'My video uploader', info: 'https://example.com/uploader', }, live: true, tag: ['tag1', 'tag2'], } ] } ] } }) ``` -------------------------------- ### Large Content Site Example Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/3.chunking-sources.md Example configuration for a large content site, specifying chunk sizes for blog posts and explicitly disabling chunking for authors. ```typescript export default defineNuxtConfig({ sitemap: { sitemaps: { 'blog-posts': { sources: ['/api/blog/posts'], chunks: 5000, }, 'authors': { sources: ['/api/authors'], chunks: false, // Explicitly disable } } } }) ``` -------------------------------- ### Configure Sitemap Products with Chunking Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/4.api/0.config.md Example of configuring a sitemap for products, specifying data sources and enabling chunking with a custom size of 5000 URLs per file. ```typescript export default defineNuxtConfig({ sitemap: { sitemaps: { products: { sources: ['/api/products'], chunks: 5000 // Split into files with 5000 URLs each } } } }) ``` -------------------------------- ### Configure Sitemap with Images Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/1.images-videos.md Example of configuring sitemap entries with image data in Nuxt. This demonstrates how to add image details to a specific sitemap location. ```typescript export default defineNuxtConfig({ sitemap: { urls: [ { loc: '/blog/my-post', images: [ { loc: 'https://example.com/image.jpg', caption: 'My image caption', geo_location: 'My image geo location', title: 'My image title', license: 'My image license', } ] } ] } }) ``` -------------------------------- ### Configure Custom Cache Storage Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/5.releases/8.v3.md Provide a custom cache instance by setting the `runtimeCacheStorage` configuration option. This example uses Redis for caching. ```typescript export default defineNuxtConfig({ sitemap: { runtimeCacheStorage: { driver: 'redis', host: 'localhost', port: 6379, db: 0, } } }) ``` -------------------------------- ### Configure Sitemap Posts with Chunking and Specific Chunk Size Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/4.api/0.config.md Example of configuring a sitemap for posts, enabling chunking and explicitly setting the chunk size to 2500 URLs. ```typescript export default defineNuxtConfig({ sitemap: { sitemaps: { posts: { sources: ['/api/posts'], chunks: true, // Enable chunking chunkSize: 2500 // Use 2500 URLs per chunk } } } }) ``` -------------------------------- ### Custom Cache Driver Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/2.performance.md Example of customizing the cache engine by setting the `runtimeCacheStorage` option, using a Cloudflare KV binding. ```typescript export default defineNuxtConfig({ sitemap: { // cloudflare kv binding example runtimeCacheStorage: { driver: 'cloudflare-kv-binding', binding: 'OG_IMAGE_CACHE' } } }) ``` -------------------------------- ### Cache Time Configuration Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/2.performance.md Example of changing the cache time by setting the `cacheMaxAgeSeconds` option. ```typescript export default defineNuxtConfig({ sitemap: { cacheMaxAgeSeconds: 3600 // 1 hour } }) ``` -------------------------------- ### Chunking by Type and Pagination Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/2.performance.md Example of splitting sitemaps further by chunking by type and a pagination format, such as by creation year. ```typescript export default defineNuxtConfig({ sitemaps: { sitemaps: { posts2020: { sources: [ 'https://api.something.com/urls?filter[yearCreated]=2020' ] }, posts2021: { sources: [ 'https://api.something.com/urls?filter[yearCreated]=2021' ] }, }, }, }) ``` -------------------------------- ### Add Page to Sitemap via YAML Frontmatter Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/4.content.md Define sitemap properties for a page using YAML frontmatter in `.yml` files. This example sets lastmod, changefreq, and priority. ```yaml title: About Page description: Learn more about us sitemap: lastmod: 2025-05-13 changefreq: monthly priority: 0.8 content: | This is the about page content ``` -------------------------------- ### Set Default Sitemap Chunk Size and Override for Specific Sitemaps Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/4.api/0.config.md Example demonstrating how to set a global default chunk size for multi-sitemaps and override it for specific sitemaps. ```typescript export default defineNuxtConfig({ sitemap: { defaultSitemapsChunkSize: 5000, sitemaps: { // These will use 5000 as chunk size posts: { sources: ['/api/posts'], chunks: true }, // This overrides the default products: { sources: ['/api/products'], chunks: 10000 } } } }) ``` -------------------------------- ### Configure Sitemap Cache TTL Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/5.releases/8.v3.md Set the cache time for production sitemaps or disable caching by configuring the `cacheTtl` option. This example sets the cache to 5 hours. ```typescript export default defineNuxtConfig({ sitemap: { cacheTtl: 5 * 60 * 60 * 1000 // 5 hours } }) ``` -------------------------------- ### Handle Sitemap Prerender Done Event Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/4.api/1.nuxt-hooks.md Use the 'sitemap:prerender:done' hook to access generated sitemaps after prerendering. This example logs the name and byte size of each generated sitemap. This hook only runs at build time. ```typescript export default defineNuxtConfig({ hooks: { 'sitemap:prerender:done': async ({ sitemaps }) => { // Log sitemap info for (const sitemap of sitemaps) { console.log(`Sitemap ${sitemap.name}: ${sitemap.content.length} bytes`) } } } }) ``` -------------------------------- ### Generate Sitemap URLs from Nuxt Content Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/4.content.md Dynamically generate sitemap URLs by querying Nuxt Content files. This example filters for articles and formats the output for the sitemap. ```typescript import type { ParsedContent } from '@nuxt/content/dist/runtime/types' import { serverQueryContent } from '#content/server' import { asSitemapUrl, defineSitemapEventHandler } from '#imports' import { defineEventHandler } from 'h3' export default defineSitemapEventHandler(async (e) => { const contentList = (await serverQueryContent(e).find()) as ParsedContent[] return contentList .filter(c => c._path.startsWith('_articles')) .map((c) => { return asSitemapUrl({ loc: `/blog/${c._path.replace('_articles', '')}`, lastmod: updatedAt }) }) }) ``` -------------------------------- ### Filter Video Entries by Host Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/5.nitro-api/nitro-hooks.md Use the 'sitemap:resolved' hook to filter video entries based on their host. This example ensures that only videos from 'www.youtube.com' are included. ```typescript import { defineNitroPlugin } from 'nitropack/runtime' export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('sitemap:resolved', (ctx) => { ctx.urls.map((url) => { if (url.videos?.length) { url.videos = url.videos.filter((video) => { if (video.content_loc) { const url = new URL(video.content_loc) return url.host.startsWith('www.youtube.com') } return false }) } return url }) }) }) ``` -------------------------------- ### Named Sitemap Chunks Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/2.performance.md Example of using the `sitemaps` option to create named sitemap chunks, with each sitemap containing its own sources. ```typescript export default defineNuxtConfig({ sitemap: { sitemaps: { posts: { sources: [ 'https://api.something.com/urls' ] }, }, }, }) ``` -------------------------------- ### Nuxt Content v2 Setup for Sitemap Exclusions Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/4.content.md Ensure Document Driven mode or `strictNuxtContentPaths` is enabled in `nuxt.config.ts` for `sitemap: false` to function correctly with Nuxt Content v2. ```typescript export default defineNuxtConfig({ content: { documentDriven: true }, // OR sitemap: { strictNuxtContentPaths: true } }) ``` -------------------------------- ### Customize Prerender Data with Nitro Hooks Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/5.prerendering.md Extend Nuxt's prerendering by using Nitro hooks to intercept and modify prerender data. This example extracts YouTube video iframes and adds them to the sitemap's video entries. ```typescript import type { ResolvedSitemapUrl } from '#sitemap/types' export default defineNuxtConfig({ modules: [ // run this before the sitemap module (_, nuxt) => { nuxt.hooks.hook('nitro:init', async (nitro) => { nitro.hooks.hook('prerender:generate', async (route) => { const html = route.contents // check for youtube video iframes and append to the videos array const matches = html.match(//g) if (matches) { const sitemap = route._sitemap || {} as ResolvedSitemapUrl sitemap.videos = sitemap.videos || [] for (const match of matches) { const videoId = match.match(/youtube.com\/embed\/(.*?)" /)[1] sitemap.videos.push({ title: 'YouTube Video', description: 'A video from YouTube', content_loc: `https://www.youtube.com/watch?v=${videoId}`, thumbnail_loc: `https://img.youtube.com/vi/${videoId}/0.jpg`, }) } // the sitemap module should be able to pick this up route._sitemap = sitemap } }) }) }, ], }) ``` -------------------------------- ### Build-time URLs with Simple Strings Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/0.getting-started/2.data-sources.md Configure build-time sitemap URLs by providing an array of path strings to the `urls` option. ```typescript export default defineNuxtConfig({ sitemap: { urls: ['/about', '/contact', '/products/special-offer'] } }) ``` -------------------------------- ### Runtime Sources with Single Sitemap Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/0.getting-started/2.data-sources.md Configure runtime sitemap sources using the `sources` array. Each source can be a URL to a JSON array or an XML sitemap. ```typescript export default defineNuxtConfig({ sitemap: { sources: [ // create our own API endpoints '/api/__sitemap__/urls', // use a static remote file 'https://cdn.example.com/my-urls.json', // hit a remote API with credentials ['https://api.example.com/pages/urls', { headers: { Authorization: 'Bearer ' } }] ] } }) ``` -------------------------------- ### Configuration Options Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/4.api/0.config.md Overview of the configuration options available for the Nuxt Sitemap module. ```APIDOC ## Configuration Options ### `enabled` - Type: `boolean` - Default: `true` Whether to generate the sitemap. ### `sortEntries` - Type: `boolean` - Default: `true` Whether the sitemap entries should be sorted or be shown in the order they were added. When enabled the entries will be sorted by the `loc`, they will be sorted by the path segment count and then alphabetically using `String.localeCompare` to ensure numbers are sorted correctly. ### `sources` - Type: `SitemapSource[]` - Default: `[]` The sources to use for the sitemap. See [Data Sources](/docs/sitemap/getting-started/data-sources) and [Dynamic URL Endpoint](/docs/sitemap/guides/dynamic-urls) for details. ### `excludeAppSources` - Type: `true | AppSourceContext[]` - Default: `[]` Whether to exclude [app sources](/docs/sitemap/getting-started/data-sources) from the sitemap. ### `appendSitemaps` - Type: `(string | { sitemap: string, lastmod?: string })[]` - Default: `undefined` Sitemaps to append to the sitemap index. This will only do anything when using multiple sitemaps. ### `autoLastmod` - Type: `boolean` - Default: `false` Sets the current date as the default `lastmod` for all entries that don't already have one. ### `sitemaps` - Type: `boolean | Record & { index?: (string | SitemapIndexEntry)[] }` - Default: `false` Whether to generate multiple sitemaps. Each sitemap can have the following options: #### `SitemapConfig` ##### `sources` - Type: `SitemapSource[]` - Default: `[]` Data sources for this specific sitemap. ##### `chunks` - Type: `boolean | number` - Default: `undefined` Enable chunking for sitemap sources. This splits large collections of URLs from sources into multiple smaller sitemap files to stay within search engine limits. - Set to `true` to enable chunking with the default chunk size (from `defaultSitemapsChunkSize` or 1000) - Set to a positive number to use that as the chunk size (e.g., `5000` for 5000 URLs per chunk) - Set to `false` or leave undefined to disable chunking Note: Chunking only applies to URLs from `sources`. Direct URLs in the `urls` property are not chunked. ```ts export default defineNuxtConfig({ sitemap: { sitemaps: { products: { sources: ['/api/products'], chunks: 5000 // Split into files with 5000 URLs each } } } }) ``` ##### `chunkSize` - Type: `number` - Default: `undefined` Explicitly set the chunk size for this sitemap. Takes precedence over the `chunks` property when both are specified. ```ts export default defineNuxtConfig({ sitemap: { sitemaps: { posts: { sources: ['/api/posts'], chunks: true, // Enable chunking chunkSize: 2500 // Use 2500 URLs per chunk } } } }) ``` See the [Chunking Sources](/docs/sitemap/advanced/chunking-sources) guide for more details. ##### `urls` - Type: `SitemapUrlInput[] | (() => SitemapUrlInput[] | Promise)` - Default: `[]` URLs to include in this sitemap. Can be strings or sitemap URL objects. ##### `include` - Type: `(string | RegExp | { regex: string })[]` - Default: `undefined` Filter URLs to include in this sitemap. ##### `exclude` - Type: `(string | RegExp | { regex: string })[]` - Default: `undefined` Filter URLs to exclude from this sitemap. ##### `defaults` - Type: `SitemapItemDefaults` - Default: `{}` Default values for all URLs in this sitemap. ##### `includeAppSources` - Type: `boolean` - Default: `false` Whether to include automatic app sources in this sitemap. See [Multi Sitemaps](/docs/sitemap/guides/multi-sitemaps) for details. ### `defaultSitemapsChunkSize` - Type: `number | false` - Default: `1000` The default chunk size when chunking is enabled for multi-sitemaps. This value is used when: - A sitemap has `chunks: true` (without specifying a number) - No `chunkSize` is explicitly set for the sitemap Set to `false` to disable chunking by default for all sitemaps. ```ts export default defineNuxtConfig({ sitemap: { defaultSitemapsChunkSize: 5000, sitemaps: { // These will use 5000 as chunk size posts: { sources: ['/api/posts'], chunks: true }, // This overrides the default products: { sources: ['/api/products'], chunks: 10000 } } } }) ``` ### `defaults` - Type: `object` - Default: `{}` Default values for the sitemap.xml entries. See [sitemaps.org](https://www.sitemaps.org/protocol.html) for all available options. ### `urls` - Type: `MaybeFunction>` - Default: `[]` Provide custom URLs to be included in the sitemap.xml. ``` -------------------------------- ### Build-time URLs with Async Function Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/0.getting-started/2.data-sources.md Use an async function for the `urls` option to fetch sitemap data at build time. It should return an array of path strings or URL objects. ```typescript export default defineNuxtConfig({ sitemap: { urls: async () => { const response = await fetch('https://api.example.com/posts') const posts = await response.json() return posts.map(post => ({ loc: `/blog/${post.slug}`, lastmod: post.updated_at, })) } } }) ``` -------------------------------- ### Customize Sitemap XML Columns Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/5.releases/8.v3.md Customize the columns displayed in the sitemap.xml UI by configuring the `xslColumns` option. This example limits columns to 'URL' and 'Last Modified'. ```typescript export default defineNuxtConfig({ sitemap: { xslColumns: [ // URL column must always be set, no value needed { label: 'URL', width: '75%' }, { label: 'Last Modified', value: 'sitemap:lastmod', width: '25%' }, ], }, }) ``` -------------------------------- ### Simple Video Integration in HTML Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/1.images-videos.md Embed a video with essential attributes like controls, poster, width, and source. Ensure 'data-title' and 'data-description' are provided for sitemap generation. ```html ``` -------------------------------- ### Basic Source Implementation Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/3.chunking-sources.md A basic endpoint implementation for sitemap sources that fetches product data and maps it to the required format. ```typescript export default defineEventHandler(async () => { const products = await db.products.findAll({ select: ['id', 'slug', 'updatedAt'] }) return products.map(product => ({ loc: `/products/${product.slug}`, lastmod: product.updatedAt })) }) ``` -------------------------------- ### Add Page to Sitemap via JSON Frontmatter Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/4.content.md Include sitemap configuration directly within a JSON file for a product page. This sets the last modification date, change frequency, and priority. ```json { "title": "Widget Product", "price": 99.99, "sitemap": { "lastmod": "2025-05-14", "changefreq": "weekly", "priority": 0.9 } } ``` -------------------------------- ### Manual Chunking Configuration Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/2.multi-sitemaps.md Configure manual chunking for sitemaps by defining specific sitemap configurations for different content types like 'posts' and 'pages'. ```typescript export default defineNuxtConfig({ sitemap: { // manually chunk into multiple sitemaps sitemaps: { posts: { include: [ '/blog/**', ], // example: give blog posts slightly higher priority (this is optional) defaults: { priority: 0.7 }, }, pages: { exclude: [ '/blog/**', ] }, }, }, }) ``` -------------------------------- ### Add @nuxtjs/sitemap using skilld Source: https://github.com/nuxt-modules/sitemap/blob/main/README.md Generate an Agent Skill for the @nuxtjs/sitemap package using the skilld CLI tool. ```bash npx skilld add @nuxtjs/sitemap ``` -------------------------------- ### Modify Sitemap xmlns Attribute Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/5.nitro-api/nitro-hooks.md Customize the `xmlns` attribute of the sitemap XML by using the 'sitemap:output' hook for search engine compatibility. This example adds a mobile schema namespace. ```typescript import { defineNitroPlugin } from 'nitropack/runtime' export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('sitemap:output', async (ctx) => { ctx.sitemap = ctx.sitemap.replace(' { const posts = await $fetch('https://api.example.com/posts') return posts.map(post => ({ loc: `/blog/${post.slug}`, lastmod: post.updated_at, })) }) ``` -------------------------------- ### Prerender Sitemap on Build Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/5.prerendering.md Add the sitemap XML path to `nitro.prerender.routes` in your Nuxt configuration to ensure the sitemap itself is prerendered during the build process. ```typescript export default defineNuxtConfig({ nitro: { prerender: { routes: ['/sitemap.xml'] } } }) ``` -------------------------------- ### Define Multiple Sitemaps Endpoint Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/0.dynamic-urls.md Fetch data from multiple sources asynchronously and map them to different sitemaps. Ensure URLs are transformed to match your domain structure and assign them to the correct `_sitemap`. ```typescript import type { SitemapUrl } from '#sitemap/types' // server/api/__sitemap__/urls.ts import { defineSitemapEventHandler } from '#imports' export default defineSitemapEventHandler(async () => { const [posts, pages] = await Promise.all([ $fetch<{ path: string, slug: string }[]>('https://api.example.com/posts') .then(posts => posts.map(p => ({ loc: `/blog/${p.slug}`, _sitemap: 'posts', } satisfies SitemapUrl))), $fetch<{ path: string }[]>('https://api.example.com/pages') .then(pages => pages.map(p => ({ loc: p.path, _sitemap: 'pages', } satisfies SitemapUrl))), ]) return [...posts, ...pages] }) ``` -------------------------------- ### Configure Sitemap Options in Page Meta Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/5.releases/3.v8.md Set sitemap configuration options such as `changefreq` and `priority` directly within your page components using `definePageMeta`. ```vue ``` -------------------------------- ### Modify URLs with 'sitemap:resolved' Hook Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/5.nitro-api/nitro-hooks.md The 'sitemap:resolved' hook allows modification or removal of URLs after the final XML structure is generated. For new URLs, 'sitemap:input' is recommended. This example shows adding a URL to a single sitemap and conditionally adding to a named sitemap. ```typescript import { defineNitroPlugin } from 'nitropack/runtime' export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('sitemap:resolved', async (ctx) => { // single sitemap example - just add the url directly ctx.urls.push({ loc: '/my-secret-url', changefreq: 'daily', priority: 0.8, }) // multi sitemap example - filter for a sitemap name if (ctx.sitemapName === 'posts') { ctx.urls.push({ loc: '/posts/my-post', changefreq: 'daily', priority: 0.8, }) } }) }) ``` -------------------------------- ### Runtime Sources with Multiple Sitemaps Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/0.getting-started/2.data-sources.md Define multiple named sitemaps, each with its own set of runtime `sources`, using the `sitemaps` configuration object. ```typescript export default defineNuxtConfig({ sitemap: { sitemaps: { foo: { sources: [ '/api/__sitemap__/urls/foo', ] }, bar: { sources: [ '/api/__sitemap__/urls/bar', ] } } } }) ``` -------------------------------- ### Enable Zero Runtime Sitemap Generation Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/6.best-practices.md Enable `zeroRuntime` to generate sitemaps at build time, ideal for sites where content only changes on deploy. This removes runtime sitemap code from your server bundle. ```typescript export default defineNuxtConfig({ sitemap: { zeroRuntime: true } }) ``` -------------------------------- ### Module Load Order for Sitemap and Content Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/4.content.md Ensure the `@nuxtjs/sitemap` module is listed before the `@nuxt/content` module in your `nuxt.config.ts` to guarantee correct loading order and functionality. ```typescript export default defineNuxtConfig({ modules: [ '@nuxtjs/sitemap', // Must be before @nuxt/content '@nuxt/content' ] }) ``` -------------------------------- ### Nitro Hook: sitemap:output Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/5.nitro-api/nitro-hooks.md Triggered before the sitemap is sent to the client. It provides the sitemap as a XML string. ```APIDOC ## Nitro Hook: sitemap:output ### Description Triggered before the sitemap is sent to the client. It provides the sitemap as a XML string. ### Method `hook` ### Event `sitemap:output` ### Parameters #### Context Object - **event** (H3Event) - The H3 event object. - **sitemap** (string) - The sitemap XML content as a string. - **sitemapName** (string) - The name of the current sitemap being processed. ### Request Example ```ts [server/plugins/sitemap.ts] import { defineNitroPlugin } from 'nitropack/runtime' export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('sitemap:output', async (ctx) => { // append a comment credit to the footer of the xml ctx.sitemap = `${ctx.sitemap}\n` }) }) ``` ``` -------------------------------- ### Custom Sitemaps with I18n Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/3.i18n.md Configure custom sitemaps alongside automatic i18n multi-sitemaps. When `includeAppSources` is true, per-locale sitemaps are generated and filters are merged. ```typescript export default defineNuxtConfig({ sitemap: { sitemaps: { pages: { includeAppSources: true, exclude: ['/admin/**'], }, posts: { sources: ['/api/__sitemap__/posts'], } } } }) ``` -------------------------------- ### Configure Sitemap Options with defineRouteRules Macro Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/0.loc-data.md Use the experimental `defineRouteRules()` macro in Vue components to configure sitemap attributes like changefreq and priority for the current route. ```vue ``` -------------------------------- ### Chunk Size Options Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/3.chunking-sources.md Configure chunk sizes using different approaches: global default, boolean (applies default), number as size, or explicit `chunkSize` (highest priority). ```typescript export default defineNuxtConfig({ sitemap: { // Global default defaultSitemapsChunkSize: 5000, sitemaps: { // Using boolean (applies default) posts: { sources: ['/api/posts'], chunks: true, }, // Using number as size products: { sources: ['/api/products'], chunks: 10000, }, // Using explicit chunkSize (highest priority) articles: { sources: ['/api/articles'], chunks: true, chunkSize: 2000, } } } }) ``` -------------------------------- ### Enable Sitemap Chunking with Custom Sizes Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/2.multi-sitemaps.md Configure chunking for specific sitemaps with default or custom chunk sizes. This is useful when dealing with sources that return a large number of URLs. ```typescript export default defineNuxtConfig({ sitemap: { sitemaps: { posts: { sources: ['/api/posts'], // returns 10,000 posts chunks: true, // Enable chunking with default size (1000) }, products: { sources: ['/api/products'], // returns 50,000 products chunks: 5000, // Chunk into files with 5000 URLs each }, articles: { sources: ['/api/articles'], chunks: true, chunkSize: 2000, // Alternative way to specify chunk size } } }, }) ``` -------------------------------- ### Defining Custom Sitemap Sources with URLs and Endpoints Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/2.multi-sitemaps.md Configure sitemaps to use static URLs or fetch dynamic URLs from specified API endpoints. ```typescript export default defineNuxtConfig({ sitemap: { sitemaps: { posts: { urls() { // resolved when the sitemap is shown return ['/foo', '/bar'] }, sources: [ '/api/sitemap-urls' ] }, }, }, }) ``` -------------------------------- ### Include Specific Routes in Sitemap Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/4.api/0.config.md Use the `include` option to specify an array of routes that should be included in the sitemap. If this array is empty, all routes are included by default. ```typescript export default defineNuxtConfig({ sitemap: { include: [ '/my-hidden-url' ] } }) ``` -------------------------------- ### Source Implementation with Caching and Streaming Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/3.chunking-sources.md For large datasets, use caching and streaming with `defineCachedEventHandler` to improve performance and manage memory usage. ```typescript export default defineCachedEventHandler(async () => { const products = [] const cursor = db.products.cursor({ select: ['slug', 'updatedAt'] }) for await (const product of cursor) { products.push({ loc: `/products/${product.slug}`, lastmod: product.updatedAt }) } return products }, { maxAge: 60 * 60, // 1 hour cache name: 'sitemap-products' }) ``` -------------------------------- ### Define Simple Sitemap Endpoint Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/0.dynamic-urls.md Use `defineSitemapEventHandler` to create a type-safe sitemap endpoint that returns a list of URLs. Specify which sitemap a URL belongs to using `_sitemap`. ```typescript import type { SitemapUrlInput } from '#sitemap/types' // server/api/__sitemap__/urls.ts import { defineSitemapEventHandler } from '#imports' export default defineSitemapEventHandler(() => { return [ { loc: '/about-us', // Specify which sitemap this URL belongs to _sitemap: 'pages', }, ] satisfies SitemapUrlInput[] }) ``` -------------------------------- ### Minimal Nuxt Sitemap Configuration Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/0.getting-started/1.installation.md Configure the Nuxt Sitemap module in your nuxt.config.ts file. At a minimum, you must provide a 'siteUrl' to ensure correct domain usage in production. ```typescript export default defineNuxtConfig({ modules: [ '@nuxtjs/sitemap', ], // Sitemap configuration sitemap: { siteUrl: 'https://your-domain.com', }, }) ``` -------------------------------- ### Configure Sitemap Sources Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/4.content.md Configure the sitemap module to use a custom API endpoint for generating sitemap URLs, useful for dynamic content. ```typescript export default defineNuxtConfig({ sitemap: { sources: [ '/api/__sitemap__/urls' ] } }) ``` -------------------------------- ### Debugging Configuration Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/3.chunking-sources.md Enable debugging to check chunk configuration and performance. Visit `/__sitemap__/debug.json` to see chunk details and generation metrics. ```typescript export default defineNuxtConfig({ sitemap: { debug: true, sitemaps: { products: { sources: ['/api/products'], chunks: 5000 } } } }) ``` -------------------------------- ### Enable Prerendering with Nuxt Config Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/5.prerendering.md Configure Nuxt to prerender routes by setting `nitro.prerender.crawlLinks` to `true` and specifying routes. This is often enabled by default with `nuxt generate`. ```typescript export default defineNuxtConfig({ nitro: { prerender: { // enabled by default with nuxt generate, not required crawlLinks: true, // add any routes to prerender routes: ['/'] } } }) ``` -------------------------------- ### Module Order for Nuxt Content v3 Integration Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/4.content.md Ensure the sitemap module is loaded before the content module in your Nuxt configuration for proper integration. ```typescript export default defineNuxtConfig({ modules: [ '@nuxtjs/sitemap', '@nuxt/content' // <-- Must be after @nuxtjs/sitemap ] }) ``` -------------------------------- ### Enable Strict Nuxt Content Paths Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/4.content.md Enable `strictNuxtContentPaths` if not using Document Driven mode and your content paths match their real paths for sitemap integration. ```typescript export default defineNuxtConfig({ sitemap: { strictNuxtContentPaths: true } }) ``` -------------------------------- ### Update dynamicUrlsApiEndpoint to sources Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/5.releases/4.v7.md Replace the dynamicUrlsApiEndpoint configuration with the sources array, which supports multiple API endpoints. ```javascript export default defineNuxtConfig({ sitemap: { - dynamicUrlsApiEndpoint: '/__sitemap/urls', + sources: ['/__sitemap/urls'] } }) ``` -------------------------------- ### Skipping the index source fetch (`chunkCount`) Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/3.chunking-sources.md Declare `chunkCount` upfront to skip the sitemap index's source fetch for counting URLs, which can be a bottleneck at very large scale. The index will emit the declared number of `` entries. ```typescript export default defineNuxtConfig({ sitemap: { sitemaps: { posts: { sources: ['/api/posts'], chunks: 5000, chunkCount: 100, // 100 chunk entries, no source fetch in the index }, }, }, }) ``` -------------------------------- ### Add Page to Sitemap via Markdown Frontmatter Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/4.content.md Use the `sitemap` key in Markdown frontmatter to specify sitemap properties like location, last modification date, change frequency, and priority. ```markdown --- loc: /my-page lastmod: 2021-01-01 changefreq: monthly priority: 0.8 --- # My Page ``` -------------------------------- ### Nitro Hook: sitemap:input Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/5.nitro-api/nitro-hooks.md Triggers once the raw list of URLs is collected from sources. Best used for inserting new URLs into the sitemap. ```APIDOC ## Nitro Hook: sitemap:input ### Description Triggers once the raw list of URLs is collected from sources. This hook is best used for inserting new URLs into the sitemap. ### Method `hook` ### Event `sitemap:input` ### Parameters #### Context Object - **event** (H3Event) - The H3 event object. - **urls** (SitemapUrlInput[]) - An array of URLs to be included in the sitemap. Can be strings or objects with `loc`, `changefreq`, and `priority`. - **sitemapName** (string) - The name of the current sitemap being processed. ### Request Example ```ts [server/plugins/sitemap.ts] import { defineNitroPlugin } from 'nitropack/runtime' export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('sitemap:input', async (ctx) => { // SitemapUrlInput is either a string ctx.urls.push('/foo') // or an object with loc, changefreq, and priority ctx.urls.push({ loc: '/bar', changefreq: 'daily', priority: 0.8, }) }) }) ``` ``` -------------------------------- ### Simple Configuration Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/2.advanced/3.chunking-sources.md Enable chunking on any named sitemap with sources using the `chunks: true` option. This uses the default chunk size of 1000. ```typescript export default defineNuxtConfig({ sitemap: { sitemaps: { posts: { sources: ['/api/posts'], chunks: true, // Uses default size of 1000 } } } }) ``` -------------------------------- ### Customizing Sitemap URLs Prefix Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/2.multi-sitemaps.md Customize the base path for multi-sitemaps. Set `sitemapsPathPrefix` to '/' to serve them at the root or `false` to disable the prefix. ```typescript export default defineNuxtConfig({ sitemap: { sitemapsPathPrefix: '/', // or false sitemaps: { // will be available at /sitemap-foo.xml 'sitemap-foo': { // ... } } } }) ``` -------------------------------- ### Enable Prerendering with Route Rules Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/5.prerendering.md Use route rules in `nuxt.config.ts` to enable prerendering for specific routes. This provides granular control over which pages are prerendered. ```typescript export default defineNuxtConfig({ routeRules: { '/': { prerender: true } } }) ``` -------------------------------- ### sitemap:sources Hook Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/5.nitro-api/nitro-hooks.md This hook is triggered before resolving sitemap sources. It allows dynamic addition, removal, or modification of source configurations, including fetch options and headers. ```APIDOC ## `sitemap:sources` Hook ### Description Triggered before resolving sitemap sources. Allows dynamic addition, removal, or modification of source configurations, including fetch options and headers. ### Method `async (ctx: { event: H3Event; sitemapName: string; sources: SitemapSourceInput[] }) => void | Promise` ### Parameters #### Context (`ctx`) - **event** (`H3Event`) - The H3 event object. - **sitemapName** (`string`) - The name of the sitemap being processed. - **sources** (`SitemapSourceInput[]`) - An array of sitemap sources. This array can be modified. ### Request Example ```ts // server/plugins/sitemap.ts import { defineNitroPlugin } from 'nitropack/runtime' export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('sitemap:sources', async (ctx) => { // Add a source that will be fetched ctx.sources.push('/api/dynamic-urls') // Add a source with fetch options ctx.sources.push(['/api/authenticated-urls', { headers: { 'X-Api-Key': 'secret' } }]) // Add a resolved source with URLs directly (no fetch needed) ctx.sources.push({ context: { name: 'my-custom-source' }, urls: ['/page-1', '/page-2', { loc: '/page-3', priority: 0.8 }], }) // Modify existing sources to add headers ctx.sources = ctx.sources.map((source) => { if (typeof source === 'object' && 'fetch' in source && source.fetch) { const [url, options = {}] = Array.isArray(source.fetch) ? source.fetch : [source.fetch, {}] // Add headers from original request const authHeader = ctx.event.node.req.headers.authorization if (authHeader) { options.headers = options.headers || {} options.headers.Authorization = authHeader } source.fetch = [url, options] } return source }) // Filter out sources ctx.sources = ctx.sources.filter((source) => { if (typeof source === 'string') return !source.includes('skip-this') return true }) }) }) ``` ``` -------------------------------- ### Configure Individual Sitemap API Endpoints Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/5.releases/8.v3.md Assign a unique API endpoint for each sitemap to fetch URLs from by using the `dynamicUrlsApiEndpoint` configuration within the `sitemaps` object. ```typescript export default defineNuxtConfig({ sitemap: { sitemaps: { foo: { dynamicUrlsApiEndpoint: '/api/foo-sitemap' }, bar: { dynamicUrlsApiEndpoint: '/api/bar-sitemap' }, }, } }) ``` -------------------------------- ### Define Dynamic i18n Sitemap Endpoint Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/0.dynamic-urls.md Fetch data for each locale from an API endpoint and construct sitemap URLs with alternative links for internationalization. Ensure `_sitemap` is explicitly mapped using ISO locales. ```typescript import type { SitemapUrl } from '#sitemap/types' // server/api/__sitemap__/urls.ts import { defineSitemapEventHandler } from '#imports' export default defineSitemapEventHandler(async () => { const config = useRuntimeConfig() const baseUrl = config.public.siteUrl const locales = config.public.i18n.locales.map(locale => locale.code) const isoLocales = Object.fromEntries( config.public.i18n.locales.map(locale => ([locale.code, locale.iso])) ) // Example: Fetch data for each locale const apiQueries = locales.map(locale => $fetch(`${config.public.apiEndpoint}/sitemap/${locale}/products`) ) const sitemaps = await Promise.all(apiQueries) return sitemaps.flat().map(entry => ({ // explicit sitemap mapping _sitemap: isoLocales[entry.locale], loc: `${baseUrl}/${entry.locale}/product/${entry.url}`, alternatives: entry.alternates?.map(alt => ({ hreflang: isoLocales[alt.locale], href: `${baseUrl}/${alt.locale}/product/${alt.url}` })) } satisfies SitemapUrl)) }) ``` -------------------------------- ### Directing URLs to Specific Sitemaps using `_sitemap` Key Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/2.multi-sitemaps.md Use the `_sitemap` key in API routes to direct specific URLs to designated sitemaps when using global sources. ```typescript export default defineNuxtConfig({ sitemap: { sources: [ '/api/sitemap-urls' ], sitemaps: { pages: { includeAppSources: true, exclude: ['/**'] // ... }, }, }, }) ``` ```typescript export default defineSitemapEventHandler(() => { return [ { loc: '/about-us', // will end up in the pages sitemap _sitemap: 'pages', } ] }) ``` -------------------------------- ### Setting Default Priority for Sitemap Entries Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/2.multi-sitemaps.md Define default values for sitemap entries within a specific sitemap configuration, such as setting a default priority. ```typescript export default defineNuxtConfig({ sitemap: { sitemaps: { posts: { // posts low priority defaults: { priority: 0.7 }, }, }, }, }) ``` -------------------------------- ### Automatic Chunking Configuration Source: https://github.com/nuxt-modules/sitemap/blob/main/docs/content/1.guides/2.multi-sitemaps.md Enable automatic chunking for sitemaps by setting `sitemaps` to true. You can also adjust the default chunk size. ```typescript export default defineNuxtConfig({ sitemap: { sitemaps: true, // modify the chunk size if you need defaultSitemapsChunkSize: 2000 // default 1000 }, }) ```