How do you implement a sitemap in Next.js?

Create app/sitemap.ts that default-exports a function returning an array of { url, lastModified, changeFrequency, priority } entries (type MetadataRoute.Sitemap). Next.js serves it as /sitemap.xml. For large sites, generateSitemaps splits it into multiple files, and a static app/sitemap.xml file also works.

Basics

  • The function can be async and fetch from your CMS or database.
  • It is a special Route Handler, cached by default unless it uses request-time APIs.
  • Fields: url (absolute), lastModified, changeFrequency, priority, alternates.languages (hreflang), images and videos.

Large sites

  • Google limits a sitemap to 50,000 URLs.
  • Export generateSitemaps() returning [{ id: 0 }, { id: 1 }, ...]. Each produces /sitemap/0.xml, /sitemap/1.xml.
  • Since Next.js 16, the sitemap function receives id as a Promise: const id = Number(await props.id).
  • Reference the generated sitemaps from robots.ts or a sitemap index.

Freshness

With Cache Components, put the data fetching in a "use cache" helper with cacheLife("days") and a tag, and revalidate the tag when content is published.

Tips

  • Include only canonical, indexable URLs that return 200.
  • Keep lastModified accurate; search engines largely ignore priority and changeFrequency.
  • Point to it from robots.txt and submit it in Google Search Console.

Code example

tsx
1// app/sitemap.ts
2import type { MetadataRoute } from "next";
3import { cacheLife, cacheTag } from "next/cache";
4
5const BASE = "https://acme.dev";
6
7async function getPosts() {
8 "use cache";
9 cacheLife("days");
10 cacheTag("posts");
11 return fetch("https://cms.example.com/posts?fields=slug,updatedAt").then((r) => r.json()) as Promise<
12 { slug: string; updatedAt: string }[]
13 >;
14}
15
16export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
17 const posts = await getPosts();
18 return [
19 { url: BASE, lastModified: new Date(), changeFrequency: "weekly", priority: 1 },
20 { url: `${BASE}/pricing`, changeFrequency: "monthly" },
21 ...posts.map((p) => ({
22 url: `${BASE}/blog/${p.slug}`,
23 lastModified: new Date(p.updatedAt),
24 alternates: { languages: { fr: `${BASE}/fr/blog/${p.slug}` } },
25 })),
26 ];
27}
28
29// Large sites:
30// export async function generateSitemaps() { return [{ id: 0 }, { id: 1 }]; }
31// export default async function sitemap(props: { id: Promise<string> }) { const id = Number(await props.id); ... }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app