Compose Proxy Steps
Hard · Proxy
Next.js 16 renamed middleware.ts to proxy.ts. A project has only one proxy file with one exported proxy(request) function, so apps that need auth, i18n and security headers usually compose several small steps into that one function. (NextRequest/NextResponse extend the Web Request/Response; here requests and results are plain objects.)
Implement chain(steps). It returns an async proxy function that takes a request and runs the steps in order. Each step receives a new request object whose path is the current internal path, and may return (or resolve to):
- undefined or { type: "next", headers? }: continue.
- { type: "rewrite", path, headers? }: continue, and later steps see the new path (so the order of steps matters).
- { type: "redirect", location, status? }: stop immediately.
Headers returned by steps are collected into one object with lowercase names; a later step overwrites the same name. The proxy resolves to:
- on a redirect: { type: "redirect", status: status ?? 307, location, path, headers } with the current path and the headers collected so far.
- after all steps: { type: "rewrite", path, headers } if the final path differs from originalPath, otherwise { type: "next", path, headers }.
- if a step throws or rejects: fail closed with { type: "error", status: 500, path, headers: {} } (current path).
The steps and the driver runProxy(stepNames, request) are already written.
Next: Draft Mode Preview Route