How does Next.js handle rewrites?
Rewrites map an incoming path to a different destination while the browser keeps the original URL. Define them with rewrites() in next.config.ts (static rules) or with NextResponse.rewrite() in proxy.ts (logic-based). Destinations can be internal routes or external URLs, in which case Next.js proxies the request.
Config shape
rewrites() can return an array (treated as afterFiles) or an object with three phases:
beforeFiles: checked after headers, redirects and Proxy, before files and pages. Can override existing routes.afterFiles: checked after pages andpublic/files, before dynamic routes.fallback: checked last, after dynamic routes. Useful for proxying unknown paths to a legacy app during migration.
Uses
- Clean URLs:
/docsto/docs/intro. - Incremental migration: fall back to an old site for routes not yet moved (
fallbacktohttps://legacy.example.com/:path*). - Proxying APIs:
/api/backend/:path*tohttps://api.internal.example.com/:path*, avoiding CORS. - Hiding third-party analytics endpoints behind your domain.
- Multi-zones: serving several Next.js apps under one domain.
Same syntax as redirects
:param, :path*, regex, has/missing conditions, basePath: false, locale: false.
Rewrite vs redirect
A redirect changes the URL and costs a round-trip. A rewrite is invisible to the user and has no extra round-trip.
Caveats
External rewrites add latency through your server. They are not supported with output: 'export'. Prefer Proxy when the target depends on cookies, headers or user data.
Code example
1// next.config.ts2import type { NextConfig } from "next";34const nextConfig: NextConfig = {5 async rewrites() {6 return {7 beforeFiles: [8 // Serve /docs from the intro page without changing the URL9 { source: "/docs", destination: "/docs/intro" },10 ],11 afterFiles: [12 // Proxy API calls to a backend: same origin for the browser, no CORS13 { source: "/api/backend/:path*", destination: "https://api.internal.acme.com/:path*" },14 // Analytics endpoint behind our domain15 { source: "/stats/script.js", destination: "https://plausible.io/js/script.js" },16 ],17 fallback: [18 // During migration: anything not handled by Next.js goes to the old app19 { source: "/:path*", destination: "https://legacy.acme.com/:path*" },20 ],21 };22 },23};2425export default nextConfig;
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.