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 / Stage 4

Middleware and the request pipeline

Goal: Run code before a request ever reaches a page, scoped to exactly the routes that need it, and use that position to redirect, rewrite, and set cookies/headers upstream of everything Parts 1–13 already built — on the PNR-status universe from Parts 8/9/13, which already has a cookie-reading component (PreferredLanguage) with nothing anywhere setting that cookie. This part is where it finally gets set. Time: ~6 h · Level: finished Part 13 (Route Handlers) Verified against: Next.js 16.4.6 / React 19.3.0, cacheComponents: true + partialPrefetching: true — this install's defaults since create-next-app, confirmed in TOOLING.md.

⚠️ The file this part teaches is proxy.ts, not middleware.ts. This stage's own plan (and most material you'll find online) calls this topic "Middleware" — and that name still works as a concept. But the installed version of Next.js this course is pinned to renamed the actual file convention in its major version 16. Section 1 below reproduces both names building, side by side, so this isn't taken on faith.

What you will learn

  • That middleware.ts/middleware() was deprecated and renamed to proxy.ts/proxy() in Next.js 16 — confirmed directly against this install's own docs and reproduced with two real builds, one for each name
  • The single-file convention: one proxy.ts at the project root (next to app/, not inside it), exporting one function (default or named proxy) plus an optional config
  • NextRequest/NextResponse: redirecting, rewriting, and the difference between the two as seen in a real response
  • Reading cookies/headers off the incoming NextRequest and setting new ones on the outgoing NextResponse — both landing before any page's own code runs
  • The matcher config: why an unscoped proxy runs on literally every request (including static assets), reproduced for real, and how a scoped matcher avoids it
  • Where Proxy sits in Next.js's documented request-handling order, and the one sharp edge the installed docs name for Server Actions specifically

Topics in this part

Practice

Only one proxy.ts is supported per project (the README's own section 2 already names this), so every exercise below works by temporarily replacing this harness's real proxy.ts with a scratch variant, running a real command against it, and then restoring the original file (cp a backup, or re-paste the version in examples/01-proxy.ts) before moving on — never leave a scratch variant committed. Copy the exact commands you ran and their real output into your own notes; do not type output from memory.


Exercise 1: A default export works too

Scenario: Every example in this part's README uses export function proxy(...), a named export. The installed docs say a default export is equally legal. Confirm it. What to do: Temporarily replace proxy.ts with a version using export default function proxy() { return NextResponse.next(); } (no name at all) and the same matcher this harness already uses. Build and request /status.

Sample output (run for real against this course's harness):

$ npm run build
...
ƒ Proxy (Middleware)
$ curl -s -o /dev/null -w "status=%{http_code}\n" http://localhost:PORT/status
status=200

💡 Hint: No difference at all in the route table or the response — export default and export function proxy are two equally legal ways to satisfy the same one-function-per-file convention. This course uses the named form throughout only because it reads slightly clearer next to an exported config, not because the default form is deprecated or discouraged.


Exercise 2: Matching on a has condition, not just a path

Scenario: Section 5's matcher only checked the URL path. The installed docs also support matching on the presence of a header, cookie, or query parameter via has/missing. Prove a query-param-gated matcher actually gates. What to do: Temporarily replace proxy.ts's config with a matcher entry whose source is /status and whose has array requires a debug query parameter to exist (any value). Set a response header from inside the proxy so a passed-through request is visible. Request /status with and without ?debug=1.

Sample output (run for real against this course's harness):

$ curl -s -D - -o /dev/null http://localhost:PORT/status | grep -i "x-proxy-matched-has"
(nothing — proxy did not run)
$ curl -s -D - -o /dev/null "http://localhost:PORT/status?debug=1" | grep -i "x-proxy-matched-has"
x-proxy-matched-has: 1

💡 Hint: The exact same URL path (/status) either does or doesn't invoke the proxy, purely based on whether a debug query parameter is present — proof that matcher conditions compose with more than just the path string, useful for something like "only run this expensive check when a feature flag cookie is present," without touching the proxy function's own code at all.


Exercise 3: Responding directly from Proxy — no NextResponse.next() at all

Scenario: Every example so far either passed the request through (NextResponse.next()) or redirected/rewrote it. The installed proxy.md reference's "Producing a response" section shows a fourth option: answering the request completely, from inside the proxy itself. This is the exact mechanism Part 15's auth gate will reuse. What to do: Temporarily replace proxy.ts with a version that, for exactly one path (/status/blocked-demo), returns a plain Response.json({ blocked: true }, { status: 403 }) directly — no call to any page, no NextResponse at all needed for this branch. Every other matched path should still pass through untouched.

Sample output (run for real against this course's harness):

$ curl -s -D - http://localhost:PORT/status/blocked-demo
HTTP/1.1 403 Forbidden
content-type: application/json

{"blocked":true,"reason":"demo"}
$ curl -s -o /dev/null -w "status=%{http_code}\n" http://localhost:PORT/status
status=200

💡 Hint: /status/blocked-demo has no page.tsx anywhere in this harness — and none was ever reached. The proxy answered the request itself, before the router looked for a matching file at all. This is precisely the shape Part 15 needs: check a session cookie, and if it's missing, respond (or redirect) without ever touching the protected page's own code.


Exercise 4: waitUntil — background work that outlives the response

Scenario: The installed docs describe event.waitUntil(promise) as a way to keep the proxy invocation alive for background work (logging, analytics) after the response has already been sent. Prove the work actually happens, and that the client doesn't wait for it. What to do: Temporarily replace proxy.ts with a version accepting a second event: NextFetchEvent parameter, calling event.waitUntil() with an async function that waits 300ms and then console.logs a message, while still returning NextResponse.next() immediately.

Sample output (run for real against this course's harness):

$ curl -s -o /dev/null http://localhost:PORT/status   # returns immediately
$ sleep 1
$ tail -5 server.log
[proxy waitUntil] background work finished for /status

💡 Hint: The curl command itself didn't block for 300ms — the response came back on normal time, and the log line only appeared after the fact, read from the server's own log a second later. This is the real difference between "doing work in the proxy" (which delays the response) and "scheduling work via waitUntil" (which doesn't) — useful for a real request-logging or analytics call that shouldn't cost every visitor extra latency.


Exercise 5: A plain Request, not NextRequest, still works for a simple check

Scenario: Every example elsewhere in this part imports NextRequest for its extra helpers (.nextUrl, .cookies). Exercise 3's blocking check only needed a path, though — confirm the plain Web Request (Part 13's object, no Next.js import at all) is still enough when none of NextRequest's extras are actually used. What to do: Write the Exercise 3 variant so its parameter is typed and read as a plain Request (new URL(request.url).pathname, not request.nextUrl.pathname), with no next/server import for the request type at all.

Sample output (run for real against this course's harness):

$ curl -s -D - http://localhost:PORT/status/blocked-demo
HTTP/1.1 403 Forbidden
{"blocked":true,"reason":"demo"}

💡 Hint: Identical result to Exercise 3. NextRequest is a convenience wrapper over the same underlying Request the platform already gives every handler (Part 13 made the same point about Response/NextResponse) — reach for it when its extras (typed .cookies, .nextUrl with pre-parsed query params) actually save real work, not as a default habit for every proxy file regardless of what it does.


Next

Part 15: An auth pattern

Show the solutions for Part 14 (5 files)

solutions/ex01.md

# Solution to Exercise 1

```ts
// proxy.ts (temporary replacement, restored afterward)
import { NextResponse } from "next/server";

export default function proxy() {
  return NextResponse.next();
}

export const config = { matcher: ["/status", "/status/:path*"] };
```

**Run for real against this harness:**
```text
$ npm run build
...
ƒ Proxy (Middleware)
$ npm run start -p PORT
$ curl -s -o /dev/null -w "status=%{http_code}\n" http://localhost:PORT/status
status=200
```

No difference from the named-export version anywhere — same route table
label, same successful response. `export default function proxy()` and
`export function proxy()` are both accepted; Next.js only cares that the
file has exactly one proxy function, found by either convention. This
course's own `proxy.ts` (`examples/01-proxy.ts`) was restored immediately
after this check.

solutions/ex02.md

# Solution to Exercise 2

```ts
// proxy.ts (temporary replacement, restored afterward)
import { NextResponse } from "next/server";

export function proxy() {
  const res = NextResponse.next();
  res.headers.set("x-proxy-matched-has", "1");
  return res;
}

export const config = {
  matcher: [
    {
      source: "/status",
      has: [{ type: "query", key: "debug" }],
    },
  ],
};
```

**Run for real against this harness:**
```text
$ curl -s -D - -o /dev/null http://localhost:PORT/status | grep -i "x-proxy-matched-has"
(nothing — proxy did not run)
$ curl -s -D - -o /dev/null "http://localhost:PORT/status?debug=1" | grep -i "x-proxy-matched-has"
x-proxy-matched-has: 1
```

The exact same path (`/status`) only invokes the proxy when a `debug`
query parameter is present on the request — `matcher.has` is checked
*before* the proxy function's own code ever runs, so there's no `if`
statement anywhere inside `proxy()` itself deciding this; the routing
layer decides it. Restored the original `proxy.ts` afterward.

solutions/ex03.md

# Solution to Exercise 3

```ts
// proxy.ts (temporary replacement, restored afterward)
export function proxy(request: Request) {
  const url = new URL(request.url);
  if (url.pathname === "/status/blocked-demo") {
    return Response.json({ blocked: true, reason: "demo" }, { status: 403 });
  }
}

export const config = { matcher: ["/status", "/status/:path*"] };
```
(Note: no `return` at all for any other path — a proxy function is
allowed to return `undefined`, which Next.js treats the same as an
explicit `NextResponse.next()`.)

**Run for real against this harness:**
```text
$ curl -s -D - http://localhost:PORT/status/blocked-demo
HTTP/1.1 403 Forbidden
content-type: application/json

{"blocked":true,"reason":"demo"}
$ curl -s -o /dev/null -w "status=%{http_code}\n" http://localhost:PORT/status
status=200
```

`/status/blocked-demo` has no `page.tsx` anywhere in this harness, and
the route table confirms no such page was ever built or rendered — the
403 response came entirely from the proxy itself, before the router
looked for a matching file. Every other matched path (`/status` in the
second command) passes through completely untouched. Restored the
original `proxy.ts` afterward.

solutions/ex04.md

# Solution to Exercise 4

```ts
// proxy.ts (temporary replacement, restored afterward)
import { NextResponse } from "next/server";
import type { NextFetchEvent, NextRequest } from "next/server";

export function proxy(request: NextRequest, event: NextFetchEvent) {
  event.waitUntil(
    (async () => {
      await new Promise((r) => setTimeout(r, 300));
      console.log(`[proxy waitUntil] background work finished for ${request.nextUrl.pathname}`);
    })()
  );
  return NextResponse.next();
}

export const config = { matcher: ["/status", "/status/:path*"] };
```

**Run for real against this harness:**
```text
$ curl -s -o /dev/null http://localhost:PORT/status
$ sleep 1
$ tail -5 server.log
[proxy waitUntil] background work finished for /status
```

The `curl` command returned at normal speed — it did not wait the extra
300ms. The log line only appears a moment later, read from the server's
own log on a separate check. `event.waitUntil()` tells the runtime "keep
this proxy invocation alive until this promise settles," which is what
lets the 300ms background task actually finish (and its `console.log`
actually run) even though the HTTP response it was attached to had
already gone out. Without `waitUntil`, nothing guarantees a background
promise started inside a proxy gets to finish at all once the response
is sent. Restored the original `proxy.ts` afterward.

solutions/ex05.md

# Solution to Exercise 5

```ts
// proxy.ts (temporary replacement, restored afterward) — no next/server
// import for the request type at all.
export function proxy(request: Request) {
  const { pathname } = new URL(request.url);
  if (pathname === "/status/blocked-demo") {
    return Response.json({ blocked: true, reason: "demo" }, { status: 403 });
  }
}

export const config = { matcher: ["/status", "/status/:path*"] };
```

**Run for real against this harness:**
```text
$ curl -s -D - http://localhost:PORT/status/blocked-demo
HTTP/1.1 403 Forbidden
{"blocked":true,"reason":"demo"}
```

Identical result to Exercise 3, with no `NextRequest` import anywhere in
this file — `new URL(request.url).pathname` on the plain Web `Request`
does the same job `request.nextUrl.pathname` would have. `NextRequest`'s
extras genuinely pay off for things this plain `Request` doesn't have at
all — a pre-parsed, typed `.cookies` API, `.nextUrl.searchParams` without
constructing a `URL` by hand, locale-aware matching — but a check that
only needs the pathname doesn't need any of them. Restored the original
`proxy.ts` afterward.

Common mistakes

Mistake Why it is wrong Fix
Naming the file middleware.ts and the function middleware on this pinned version Deprecated in Next.js 16 — still builds, but with a real warning naming an automatic codemod, reproduced in section 1 Name the file proxy.ts and the function proxy (default or named export, either works)
Expecting a rewrite to change what the browser's address bar shows A rewrite serves different content under the same URL — only a redirect changes the URL, section 3's real location header vs. x-middleware-rewrite header shows the difference Use NextResponse.redirect when the URL itself should change; NextResponse.rewrite when it shouldn't
Writing NextResponse.next({ headers }) to pass a header to your own app's code That form sends the header to the client, not downstream to your own routes — confirmed by the installed docs' own distinction Use NextResponse.next({ request: { headers } }) for headers your own Server Components/Route Handlers should read
Shipping a proxy with no matcher "because it's simpler" It then runs on literally every request, including static assets — reproduced for real in section 5 with a harmless header hitting both a page and /favicon.ico Always set matcher (or an explicit path check) scoped to exactly the routes the logic concerns
Assuming a matcher that covers "all of /dashboard" also covers a Server Action that used to live under /dashboard but was refactored elsewhere The installed docs state directly that Server Function calls are POST requests to wherever the action is used, and a matcher change can silently stop covering one Re-verify authentication/authorization inside the Server Function itself (Part 12's own rule), never only in the proxy
Reaching for Proxy to do a slow data fetch (a database call, an external API) before every matched request The installed docs state Proxy is "not intended for slow data fetching" and that cache-related fetch options have no effect inside it Keep Proxy logic to cheap, synchronous-feeling checks (cookie/header reads); move real data fetching into a Server Component or Route Handler downstream

Quick recap

  • This install's real file convention is proxy.ts/proxy() — middleware.ts/middleware() still builds (deprecated, Next.js 16) but prints a real warning; both were built back to back against this harness to confirm.
  • One proxy.ts at the project root, one exported function, an optional config — multiple proxy files aren't supported; compose by importing helper modules into the one entry point.
  • NextResponse.redirect changes the client-visible URL; NextResponse.rewrite serves different content under the same URL, with no client-visible sign other than an x-middleware-rewrite response header — both reproduced for real.
  • Headers/cookies can be set on the request going downstream (NextResponse.next({ request: { headers } }), read by this app's own headers() calls) or the response going to the client (response.cookies.set(...), a real Set-Cookie this part proved persists across later requests).
  • An unscoped proxy runs on every request, static assets included — reproduced for real against this harness's own /mandi and /favicon.ico. Always set a matcher.
  • Proxy runs before any route in app/ and before dynamic routes resolve, but a Server Action is "used" wherever its own route lives — a matcher refactor can silently stop covering one, which is exactly the trap Part 15's auth proxy has to avoid.

Checklist

  • I built this harness's proxy twice — once named middleware.ts/middleware, once named proxy.ts/proxy — and read the real deprecation warning (or its absence) for myself.
  • I triggered a real redirect and a real rewrite from the same proxy file and can point to the specific response header that tells them apart.
  • I set a cookie from inside a proxy and confirmed, with a second real request, that a later request with no query string at all still carried it.
  • I read a header inside a Server Component that a proxy set on the request, using the same headers() API Part 9 already taught.
  • I ran an unscoped proxy (no matcher) against this harness and watched it affect an unrelated page and a static asset, then removed it.
  • I can state, from the installed docs' own wording, why a matcher covering a page route doesn't automatically cover a Server Action that used to live under that same path.

Search the guide