Next.jsMedium
How do you rewrite URLs in middleware?
Return NextResponse.rewrite(url) from proxy.ts. Next.js serves the content of the destination route while the browser keeps showing the original URL. It is used for A/B tests, multi-tenant subdomains, localized routing and feature flags.
Redirect vs rewrite
- Redirect: the browser receives a 3xx and makes a new request; the URL bar changes.
- Rewrite: the server internally serves another path; the URL bar does not change, and there is no extra round-trip.
Typical uses
- Multi-tenancy:
acme.example.com/aboutrewrites to/sites/acme/about. - A/B testing: assign a bucket cookie and rewrite
/pricingto/pricing/b. - Locale: rewrite
/productsto/en/productsinternally based onAccept-Language, without showing the prefix. - Proxying to external services: rewrite
/blog/:path*to another origin (Next.js proxies the request).
Details
- The destination must be an absolute URL; build it with
new URL(path, request.url). - Rewrites preserve query strings unless you change them.
- For RSC requests (client navigation),
NextResponse.rewrite()forwards the required internal headers automatically. If you implement rewrites with your ownfetch, you must forward them yourself. - Static rewrites with no logic are simpler in
rewrites()innext.config.ts(beforeFiles,afterFiles,fallback).
Pitfall
<Link> prefetching sees the original URL. For links whose rewrite depends on Proxy logic, the docs show passing as and href so the prefetch uses the destination.
Code example
tsx
1// proxy.ts - multi-tenant subdomains + A/B test2import { NextResponse, type NextRequest } from "next/server";34export function proxy(request: NextRequest) {5 const host = request.headers.get("host") ?? "";6 const url = request.nextUrl;78 // tenant.example.com/* -> /sites/tenant/*9 const [subdomain] = host.split(".");10 if (host.endsWith("example.com") && subdomain !== "www" && subdomain !== "example") {11 return NextResponse.rewrite(new URL(`/sites/${subdomain}${url.pathname}`, request.url));12 }1314 // A/B test on /pricing, sticky via cookie15 if (url.pathname === "/pricing") {16 const bucket = request.cookies.get("ab-pricing")?.value ?? (Math.random() < 0.5 ? "a" : "b");17 const res = NextResponse.rewrite(new URL(`/pricing/${bucket}`, request.url));18 res.cookies.set("ab-pricing", bucket, { path: "/", maxAge: 60 * 60 * 24 * 30 });19 return res;20 }21}2223export const config = { matcher: ["/((?!_next|api|favicon.ico).*)"] };
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.