How do you implement a robots.txt in Next.js?

Add a static app/robots.txt file, or create app/robots.ts that returns a MetadataRoute.Robots object with rules, sitemap and optionally host. Next.js serves it at /robots.txt. The code version lets you vary rules by environment, for example blocking all crawlers on staging.

Fields

  • rules: one object or an array, each with userAgent, allow, disallow and optional crawlDelay.
  • sitemap: one or more absolute sitemap URLs.
  • host: preferred host (used by some search engines).

Common rules

  • Disallow private or duplicate areas: /api/, /admin/, /search? result pages, /_next/ is not needed (assets are fine to crawl).
  • Block AI training crawlers if you choose, by naming their user agents (GPTBot, CCBot, Google-Extended).
  • Staging and preview: disallow: "/" for all agents, plus an X-Robots-Tag: noindex header for safety.

Important limits

  • robots.txt controls crawling, not indexing. To keep a page out of search results, use robots: { index: false } in metadata (a noindex meta tag) and let crawlers see it.
  • It is public; never list secret URLs in it.

Pages Router

Put a static public/robots.txt, or generate one with a rewrite to an API route.

Code example

tsx
1// app/robots.ts
2import type { MetadataRoute } from "next";
3
4const BASE = "https://acme.dev";
5const isProduction = process.env.VERCEL_ENV === "production" || process.env.APP_ENV === "production";
6
7export default function robots(): MetadataRoute.Robots {
8 if (!isProduction) {
9 return { rules: { userAgent: "*", disallow: "/" } }; // keep staging out of search
10 }
11
12 return {
13 rules: [
14 { userAgent: "*", allow: "/", disallow: ["/api/", "/admin/", "/account/"] },
15 { userAgent: ["GPTBot", "CCBot"], disallow: "/" },
16 ],
17 sitemap: [`${BASE}/sitemap.xml`],
18 host: BASE,
19 };
20}
21
22// Output at /robots.txt:
23// User-Agent: *
24// Allow: /
25// Disallow: /api/
26// ...
27// Sitemap: https://acme.dev/sitemap.xml

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