Skip to content
BackendChapter 20 / 34Intermediate5 min read

Proxy (formerly Middleware)

What the Next.js proxy.ts file is, the replacement for middleware, and how it redirects, rewrites and changes headers before a request, with matcher and the Node runtime.

On this page

1. What is Proxy?

In Next.js 16, middleware.ts was renamed to proxy.ts. The job is the same, but the new name makes it clear that this is a network boundary standing in front of your app. The exported function is also named proxy.

proxy.ts always runs on the Node.js runtime. The old middleware.ts still exists only for Edge runtime cases, but it is deprecated.

2. Why does it matter?

Some decisions must be made before the page renders: which language page to send the user to, which version of an A/B test to show, sending the user to /login if they are not logged in.

Checking in every pageOne proxy.ts
Copying redirect logic into every pageCentralized logic in one place
The page render has already startedBefore the request reaches the page
Setting headers is hardCan change both request and response headers
The confusing name middleware.tsproxy.ts, Node runtime, clear purpose

3. Where is it used?

Use caseWhat Proxy does
Optimistic auth redirectSend the user to /login if there is no session cookie
i18nLook at Accept-Language and redirect to /ur or /en
A/B testingRewrite to a different page based on a cookie
Security headersAdd a custom header to every response
Old URLsRedirects with complex logic

For simple, fixed redirects, look at the redirects option in next.config.ts first. Use Proxy only when you need logic based on request data.

4. How does it work?

Proxy flow
Browser request
The matcher checks whether the path matches
The proxy function runs
NextResponse.next or redirect or rewrite
The route renders, or the new URL is served
RuleDetail
LocationIn the project root, or inside src, next to app
CountOnly one proxy.ts in the whole project
ExportA named proxy function or a default export
RuntimeNode.js
CachingThe cache options of fetch have no effect in Proxy

5. Code example

Example: auth redirect and a custom header

ts
import { NextResponse, type NextRequest } from "next/server";

const protectedPaths = ["/dashboard", "/settings"];

export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const hasSession = request.cookies.has("session");
  const isProtected = protectedPaths.some((path) => pathname.startsWith(path));

  if (isProtected && !hasSession) {
    const loginUrl = new URL("/login", request.url);
    loginUrl.searchParams.set("from", pathname);
    return NextResponse.redirect(loginUrl);
  }

  if (pathname === "/pricing" && request.cookies.get("ab")?.value === "b") {
    return NextResponse.rewrite(new URL("/pricing-b", request.url));
  }

  const response = NextResponse.next();
  response.headers.set("x-app-version", "16");
  return response;
}

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};

How does the code work?

PartMeaning
export function proxyThe new name in Next.js 16, it used to be middleware
request.nextUrl.pathnameThe current path
request.cookies.has("session")Only checks that the cookie exists, an optimistic check
NextResponse.redirect(url)The URL in the browser changes
NextResponse.rewrite(url)The URL stays the same, but another page is served behind it
NextResponse.next()Lets the request continue
config.matcherDo not run Proxy on static files and the API

Migration: from middleware.ts to proxy.ts

bash
npx @next/codemod@canary upgrade latest

The manual way: rename the file from middleware.ts to proxy.ts and the function from middleware to proxy. The logic stays the same.

Interview tip

"Is auth in Proxy enough?" Answer: no. Proxy is only for an optimistic check. Real authorization should happen close to the data, in the Data Access Layer, Server Actions and Route Handlers.

6. Common mistakes

Mistake: Turning Proxy into the whole auth system

Why? Proxy only looks at the cookie, and it can be bypassed by calling Server Actions and Route Handlers directly.

Better: Only redirect in Proxy, and verify the session in the DAL, next to the data.

Mistake: Doing a database query or a slow fetch in Proxy

Why? Proxy runs on every matching request and prefetch, so the whole app becomes slow.

Better: Decide immediately from a cookie or header only, and keep heavy work in the pages.

Mistake: Not setting a matcher

Why? Proxy also runs on images, CSS and _next files, doing work for no reason.

Better: Use the matcher to exclude static assets and paths you do not need.

Mistake: Writing new code in middleware.ts on Next.js 16

Why? middleware.ts is deprecated and will be removed in a future version.

Better: Create proxy.ts and export a function named proxy.

7. What to learn before and after

Final quick revision

PointDetail
Fileproxy.ts, in the root or in src
Functionexport function proxy(request)
RuntimeNode.js
Actionsnext(), redirect(), rewrite(), headers
Filterexport const config = { matcher }
AuthOnly optimistic, the real check is in the DAL