Course map
Stage 1: App Router Foundations
Stage 2: The Rendering Model
Stage 3: Data, Caching and Mutations
Stage 4: Full-Stack Next.js
Stage 5: Production and Specialization

Part 14 / Topic 3 of 6

Redirect vs. rewrite — the same request, two different real results

Both use a NextRequest/NextResponse pair that extends the plain Web Request/Response Part 13 already used, with routing-specific helpers added (request.nextUrl, NextResponse.redirect(...), NextResponse.rewrite(...)):

if (pathname === "/status/search") {
  return NextResponse.redirect(new URL("/status", request.url));
}
if (pathname === "/status/legacy") {
  return NextResponse.rewrite(new URL("/status", request.url));
}

Run for real against this harness:

$ curl -s -D - -o /dev/null http://localhost:PORT/status/search
HTTP/1.1 307 Temporary Redirect
location: /status

A redirect tells the client — a real browser included — to make a brand new request to a different URL; the address bar changes. A rewrite is the opposite: the client never finds out.

$ curl -s http://localhost:PORT/status/legacy | grep -o '<h1>[^<]*</h1>'
<h1>Check PNR status</h1>

/status/legacy has no page.tsx of its own anywhere in this harness — the response above is /status's own <h1>, served transparently under a URL that, in a real browser, would stay /status/legacy in the address bar. The response itself carries this out in a header a curious client can read, though the browser UI never shows it:

$ curl -s -D - http://localhost:PORT/status/legacy | grep -i "x-middleware-rewrite"
x-middleware-rewrite: /status

Done here? The practice set for Part 14 — including the solutions — is on the part page.

Search the guide