What is middleware in Next.js?

Middleware is code that runs before a request is completed, letting you redirect, rewrite, set headers or cookies, or return a response early. In Next.js 16 it was renamed to Proxy: the file is proxy.ts and the exported function is proxy. The functionality is the same, and middleware.ts still works but is deprecated.

What it is good for

  • Redirects based on request data: locale detection, old URLs, logged-out users.
  • Rewrites for A/B tests, multi-tenant subdomains or feature flags.
  • Adding headers: security headers, CSP nonces, request IDs.
  • Optimistic auth checks: redirect to /login if there is no session cookie.
  • Bot or geo handling.

What it is not for

  • Slow data fetching or full session management. Proxy runs on many requests and should be fast.
  • The only line of authorization; check permissions in pages, handlers and Server Functions too.
  • Caching: "use cache", "use server" and fetch caching options have no effect in Proxy.

Why the rename

"Middleware" suggested Express-style middleware chains. "Proxy" better describes its role: a network boundary in front of the app that can redirect, rewrite and respond.

Migration

Run npx @next/codemod@canary middleware-to-proxy ., or rename the file and the function. Config flags were renamed too, such as skipMiddlewareUrlNormalize to skipProxyUrlNormalize. Proxy runs on Node.js only; keep middleware.ts if you depend on the Edge runtime.

Code example

tsx
1// proxy.ts (Next.js 16+, formerly middleware.ts)
2import { NextResponse } from "next/server";
3import type { NextRequest } from "next/server";
4
5export function proxy(request: NextRequest) {
6 const hasSession = request.cookies.has("session");
7
8 if (!hasSession && request.nextUrl.pathname.startsWith("/dashboard")) {
9 const login = new URL("/login", request.url);
10 login.searchParams.set("next", request.nextUrl.pathname);
11 return NextResponse.redirect(login);
12 }
13
14 const response = NextResponse.next();
15 response.headers.set("x-request-id", crypto.randomUUID());
16 return response;
17}
18
19export const config = {
20 matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\.(?:png|jpg|svg)$).*)"],
21};

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.

Open in study app