Next.jsEasy
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 withuserAgent,allow,disallowand optionalcrawlDelay.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 anX-Robots-Tag: noindexheader for safety.
Important limits
robots.txtcontrols crawling, not indexing. To keep a page out of search results, userobots: { index: false }in metadata (anoindexmeta 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.ts2import type { MetadataRoute } from "next";34const BASE = "https://acme.dev";5const isProduction = process.env.VERCEL_ENV === "production" || process.env.APP_ENV === "production";67export default function robots(): MetadataRoute.Robots {8 if (!isProduction) {9 return { rules: { userAgent: "*", disallow: "/" } }; // keep staging out of search10 }1112 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}2122// 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.