More Next.js answers

by Danny
Published 2 min read

Add sitemap.ts and robots.ts files to the app folder. Next.js serves them as sitemap.xml and robots.txt, and you can build the list of URLs from your own data.

The short answer

#

Create app/sitemap.ts and app/robots.ts. Each exports a default function that returns plain data, and Next.js turns it into /sitemap.xml and /robots.txt. You do not need a plugin or a build script.


_10
// app/sitemap.ts
_10
import type { MetadataRoute } from 'next';
_10
_10
export default function sitemap(): MetadataRoute.Sitemap {
_10
return [
_10
{ url: 'https://example.com', lastModified: new Date('2026-11-01') },
_10
{ url: 'https://example.com/about', lastModified: new Date('2026-06-12') },
_10
];
_10
}

Why it happens

#

In the Pages Router, sitemaps usually came from a package such as next-sitemap that ran after the build, or from a hand-written API route. The App Router has built-in metadata files instead. sitemap.ts and robots.ts are special Route Handlers: Next.js calls your function, converts the result into the right XML or text format and sets the content type.

They are cached by default, so they are generated at build time and served as static files. They only run on every request if they use a request-time API such as cookies() or headers(), or a dynamic segment config.

If your site never changes, you can also drop a static sitemap.xml or robots.txt straight into the root of app.

How to fix it

#

Build the sitemap from your data

Most sites have static pages plus a list of posts or products. Combine both. The function can be async, so you can query a database or CMS.


_20
// app/sitemap.ts
_20
import type { MetadataRoute } from 'next';
_20
import { getAllPosts } from '@/lib/posts';
_20
_20
const baseUrl = 'https://example.com';
_20
_20
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
_20
const posts = await getAllPosts();
_20
_20
const staticPages = ['', '/about', '/blog'].map((path) => ({
_20
url: `${baseUrl}${path}`,
_20
}));
_20
_20
const postPages = posts.map((post) => ({
_20
url: `${baseUrl}/blog/${post.slug}`,
_20
lastModified: post.updatedAt,
_20
}));
_20
_20
return [...staticPages, ...postPages];
_20
}

Each entry can also have changeFrequency, priority, alternates.languages for translated pages, images and videos.

Add robots.ts and point it at the sitemap


_13
// app/robots.ts
_13
import type { MetadataRoute } from 'next';
_13
_13
export default function robots(): MetadataRoute.Robots {
_13
return {
_13
rules: {
_13
userAgent: '*',
_13
allow: '/',
_13
disallow: ['/admin/', '/api/'],
_13
},
_13
sitemap: 'https://example.com/sitemap.xml',
_13
};
_13
}

That produces:


_10
User-Agent: *
_10
Allow: /
_10
Disallow: /admin/
_10
Disallow: /api/
_10
_10
Sitemap: https://example.com/sitemap.xml

rules can also be an array, with different rules for each crawler.

Block crawlers on preview deployments

Because robots.ts is code, you can change the output by environment. Read a variable you set yourself on staging.


_10
export default function robots(): MetadataRoute.Robots {
_10
if (process.env.SITE_ENV !== 'production') {
_10
return { rules: { userAgent: '*', disallow: '/' } };
_10
}
_10
_10
return {
_10
rules: { userAgent: '*', allow: '/' },
_10
sitemap: 'https://example.com/sitemap.xml',
_10
};
_10
}

The file is generated at build time, so the variable must be set when you run next build.

Split very large sitemaps

A single sitemap can hold up to 50,000 URLs. Beyond that, export generateSitemaps and return one id per file. In Next.js 16, the id passed to your function is a Promise.


_15
// app/products/sitemap.ts
_15
import type { MetadataRoute } from 'next';
_15
_15
export async function generateSitemaps() {
_15
const count = await countProducts();
_15
return Array.from({ length: Math.ceil(count / 50000) }, (_, id) => ({ id }));
_15
}
_15
_15
export default async function sitemap(props: {
_15
id: Promise<string>;
_15
}): Promise<MetadataRoute.Sitemap> {
_15
const id = Number(await props.id);
_15
const products = await getProducts({ offset: id * 50000, limit: 50000 });
_15
return products.map((p) => ({ url: `https://example.com/products/${p.slug}` }));
_15
}

The files are served at /products/sitemap/0.xml, /products/sitemap/1.xml and so on. List each one in robots.ts or submit them in Google Search Console.

Common pitfalls

#
  • Relative URLs. Sitemap and robots entries must be absolute, including the protocol and domain. Keep the base URL in one constant.
  • Setting lastModified to new Date() for every page. That tells crawlers everything changed on every build. Use real update dates, or leave the field out.
  • Expecting Disallow to hide a page. robots.txt asks crawlers not to fetch a URL, but the URL can still appear in results if other sites link to it. To keep a page out of search, add robots: { index: false } to its metadata.
  • Putting robots.ts in a subfolder. Crawlers only read /robots.txt at the root, so the file must sit directly in app.
  • Stale sitemaps. Because the file is cached at build time, new posts appear only after the next build, unless you add revalidation.
  • Synchronous id. Code from Next.js 15 that uses id directly in a generateSitemaps sitemap must await it in Next.js 16.
#

Was this resource helpful?