---
title: "How do I add a sitemap.xml and robots.txt in the Next.js App Router?"
description: "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."
url: https://www.danny.engineering/answer/nextjs/how-do-i-add-a-sitemapxml-and-robotstxt-in-the-nextjs-app-router
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T20:30:00.000Z
tags: ["Next.js"]
---

# How do I add a sitemap.xml and robots.txt in the Next.js App Router?

## 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.


```typescript
// app/sitemap.ts
import type { MetadataRoute } from 'next';

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


## 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.


```typescript
// app/sitemap.ts
import type { MetadataRoute } from 'next';
import { getAllPosts } from '@/lib/posts';

const baseUrl = 'https://example.com';

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const posts = await getAllPosts();

  const staticPages = ['', '/about', '/blog'].map((path) => ({
    url: `${baseUrl}${path}`,
  }));

  const postPages = posts.map((post) => ({
    url: `${baseUrl}/blog/${post.slug}`,
    lastModified: post.updatedAt,
  }));

  return [...staticPages, ...postPages];
}
```


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


### Add robots.ts and point it at the sitemap


```typescript
// app/robots.ts
import type { MetadataRoute } from 'next';

export default function robots(): MetadataRoute.Robots {
  return {
    rules: {
      userAgent: '*',
      allow: '/',
      disallow: ['/admin/', '/api/'],
    },
    sitemap: 'https://example.com/sitemap.xml',
  };
}
```


That produces:


```bash
User-Agent: *
Allow: /
Disallow: /admin/
Disallow: /api/

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.


```typescript
export default function robots(): MetadataRoute.Robots {
  if (process.env.SITE_ENV !== 'production') {
    return { rules: { userAgent: '*', disallow: '/' } };
  }

  return {
    rules: { userAgent: '*', allow: '/' },
    sitemap: 'https://example.com/sitemap.xml',
  };
}
```


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.


```typescript
// app/products/sitemap.ts
import type { MetadataRoute } from 'next';

export async function generateSitemaps() {
  const count = await countProducts();
  return Array.from({ length: Math.ceil(count / 50000) }, (_, id) => ({ id }));
}

export default async function sitemap(props: {
  id: Promise<string>;
}): Promise<MetadataRoute.Sitemap> {
  const id = Number(await props.id);
  const products = await getProducts({ offset: id * 50000, limit: 50000 });
  return products.map((p) => ({ url: `https://example.com/products/${p.slug}` }));
}
```


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.

## Related reading

- [Next.js: sitemap.xml](https://nextjs.org/docs/app/api-reference/file-conventions/metadata/sitemap)
- [Next.js: robots.txt](https://nextjs.org/docs/app/api-reference/file-conventions/metadata/robots)
- [Next.js: generateSitemaps](https://nextjs.org/docs/app/api-reference/functions/generate-sitemaps)
