the writing next.js & headless 10 min

Next.js proxy.ts: What Replaced Middleware in Next.js 16

Next.js 16 renamed middleware.ts to proxy.ts. A before and after migration, matcher patterns for auth and locale redirects, and the runtime limits that matter.

Line-art browser window behind a checkpoint arch with arrows passing through, and two folders joined by an arrow

Next.js 16 renamed middleware.ts to proxy.ts , and the exported function is now called proxy. Small name, large signal. According to the Next.js 16 release post, the logic stays the same; what changes is the name and the runtime, which is now Node.js. The Proxy docs (dated 4 September 2026) mark the old convention as deprecated. Below you get the before and after migration. You also get matcher patterns for auth, locale redirects and geolocation, then a table of runtime limits and the mistakes that break things quietly. For the release as a whole, the Next.js 16 upgrade guide covers it. This post stays on one file.

Why middleware became proxy

Middleware arrived as a beta in Next.js 12 and went stable in 12.2, according to the Next.js release archive. Then the shape tightened. The 12.2 upgrade guide replaced nested _middleware.ts files with a single root file. For years it ran only on the Edge Runtime, which is why older write-ups, like Clerk's explainer, talk about a limited subset of Node.js APIs. Then Next.js 15.5 announced a stable Node.js runtime for middleware, after experimental support in 15.2.

Next.js 16 finished the thought. The release post says to rename middleware.ts to proxy.ts and the export to proxy , with the logic unchanged. Its deprecations table gives the reason clearly enough: clarify the network boundary and the routing focus. middleware.ts still exists for Edge runtime use cases, but it is deprecated and will be removed in a future version. One third-party post puts the Next.js 16 release at October 21, 2025.

My read is this. The old name sounded like an application layer, something Express-flavoured where you hang business logic. Proxy sounds like what it is: a thing in front of your routes. Auth0 describes the new name as reflecting a lightweight routing layer rather than a place for heavy business logic, and that framing is the useful bit. Treat the rename as a hint about how much work this file should do.

Renaming the file and running the codemod

The change is mostly mechanical. Here is the before and after, using the examples in the docs and the Next.js 16 post.

ThingBefore (middleware)After (proxy)
Filemiddleware.tsproxy.ts , same level as app or pages (or inside src)
Functionexport function middleware(request)export function proxy(request), or a default export
RuntimeEdge only until 15.5 made Node.js stableNode.js by default; the runtime option throws
URL flagskipMiddlewareUrlNormalizeskipProxyUrlNormalize
Matcherexport const config = { matcher }Same shape
Test helperunstable_doesMiddlewareMatchunstable_doesProxyMatch in current docs

The migration, in order:

  1. Run a codemod. Two third-party sources give two commands: npx @next/codemod@canary upgrade latest from one migration post, and npx @next/codemod@canary middleware-to-proxy . from we.inc. The second is narrower, so it's the one I'd pick.
  2. Read the diff by hand. A codemod can rename files and exports, but it can't decide whether a given rule belongs in Proxy at all (John Kavanagh makes a similar point).
  3. Rename any config flags. The docs say skipProxyUrlNormalize was formerly skipMiddlewareUrlNormalize, and both flags date back to v13.1.
  4. Delete the old middleware.ts. Then run a build and read the output.
  5. Update tests that import a matcher helper (more on that under common mistakes).

The function body doesn't change. A redirect from /about/:path* to /home is the same code with a new name on the export.

What happens to a leftover middleware.ts?

Sources disagree. One says a leftover middleware.ts is silently ignored at build time in Next.js 16. Another says the existing middleware still runs with a deprecation warning on every build, and that having both files fails the build; that author reports testing on Next.js 16.4.5, see the write-up. I can't settle that for your project, and you shouldn't need to. Rename, delete the old file, and you never depend on either behaviour.

Matcher patterns that actually work

This is where most proxy bugs live. The docs are blunt: without a matcher , Proxy runs on every request, including _next/static , _next/image and everything in public/. Auth logic or redirects can then block your CSS, JS or images. Quietly, too.

Line-art page cards with a gate in front of two of them while arrows reach the others, showing selective matching

The source pattern rules from the Proxy docs:

  • /about matches /about and /about/team , but not /blog/about. Patterns are anchored to the start of the path.
  • /about/:path matches /about/a and /about/b , but not /about/a/c.
  • /about/:path * matches /about/a/b/c , because * means zero or more. ? is zero or one, + is one or more.
  • /about/(.*) is the same as /about/:path*.
  • Every source must start with /.

For a site-wide proxy that skips the noise, the docs show a negative match: /((?!api|_next/static|_next/image|.*\\.png$).*). It excludes API routes, static files, image optimisation and .png files. For an auth gate, go the other way. List only what you protect. The we.inc examples use ["/dashboard/:path *", "/settings/:path*"], which is about as tidy as it gets.

A matcher can also be an array of objects with source , locale , has and missing . That gives you conditions on headers, query parameters or cookies. The Next.js 15 Middleware docs, last updated June 10, 2025, also list a regexp key; the current Proxy key list doesn't, so don't reach for it. The Next.js 14 docs show ignoring next/link prefetches by putting the next-router-prefetch and purpose: prefetch headers in missing . Check that still behaves on 16 before you copy it, since the Proxy docs say Flight headers like rsc and next-router-prefetch aren't exposed through request.headers during RSC requests.

One more thing. Matcher values must be constants so they can be analysed at build time. Build the array from a variable or an env lookup and Next.js ignores it. No error, just no matching.

Auth checks, and why not to trust them alone

The common pattern is an optimistic check. Look for a session cookie. If it's missing, redirect to /login with the original path in a next query parameter. The we.inc example does exactly that with request.cookies.has and a matcher limited to /dashboard and /settings. Cheap, fast, and it keeps signed-out visitors from seeing a flash of a protected page.

But a cookie existing is not a session being valid. That is the point most people miss.

There are two separate reasons not to treat Proxy as your security boundary:

  • Bypass history. CVE-2025-29927 was published on March 21, 2025 with a CVSS score of 9.1. It let attackers skip middleware with a spoofed x-middleware-subrequest header, per this migration post. Patches landed in 12.3.5, 13.5.9, 14.2.25 and 15.2.3. Patched is patched, but it shows what happens when one layer is the only layer.
  • Coverage gaps. Server Functions are handled as POST requests to the route where they're used. So if your matcher excludes a path, it also skips Server Function calls on that path. The docs warn that a matcher change, or a refactor that moves a Server Function to another route, can silently remove Proxy coverage, and tell you to verify authentication and authorisation inside each Server Function.

So: Proxy for the redirect, the data layer for the decision. Keep the boundary firm. Check the session where the data is read or the mutation runs. If you inherit a codebase with a dozen matchers and no checks in the Server Functions, that audit is the first job, and it's the kind of thing a Next.js developer can scope in a day or two of reading.

Locale redirects and geolocation

Locale routing is a fair use of Proxy, because it needs request context. The we.inc example is a good shape: define the supported list (en , es , fr ), let any path that already starts with a supported locale pass through, and redirect everything else using the first matching Accept-Language entry, falling back to en.

Two details save you pain. First, scope the matcher with the negative pattern from earlier, otherwise your locale redirect will happily try to prefix /_next/static/... and your site goes bare. Second, remember the order the docs list: headers, redirects, then Proxy, then beforeFiles rewrites, filesystem routes, afterFiles rewrites, dynamic routes, and fallback rewrites. Redirects in next.config fire before Proxy ever sees the request.

That ordering is also a design rule. John Kavanagh suggests that if a rule is static and needs no request data, it should start as a redirects entry in next.config.ts. Agreed. Use Proxy for the stuff that depends on cookies, headers or the visitor.

Geolocation

Country routing is the other classic. The same guide reads x-vercel-ip-country , checks it against a small set of EU country codes, and rewrites /pricing to /pricing/eu. The visitor keeps the clean URL. Worth knowing: that header is the one Vercel adds, and other hosts use their own header name, so check your host's docs for the right one rather than copying the string.

If you're weighing framework-level locale routing against a Proxy approach, the Astro i18n guide shows how a different stack handles it.

Runtime and performance limits

The practical reference is this. Everything comes from the Proxy docs (dated 4 September 2026) unless noted.

LimitWhat the docs say
RuntimeDefaults to Node.js
runtime configNot available; setting it throws an error
Edge needsStay on the deprecated middleware.ts, per the Next.js 16 post
ExportsOne function, default or named proxy
Argumentsrequest then event (a NextFetchEvent with waitUntil)
Matcher valuesConstants only; variables are ignored
Shared stateDon't rely on shared modules or globals
RSC requestsInternal Flight headers are stripped from request.headers
Large headersCan trigger 431 Request Header Fields Too Large, depending on backend server config

The Node.js default is a real change. Advice before 16 about no file system and no native modules, the Clerk piece is typical, described Edge-only middleware. It no longer maps cleanly to proxy.ts.

But more capability is not a licence for more work. The docs say Proxy is meant to be invoked separately from your render code, and in optimised cases deployed to your CDN for fast redirect and rewrite handling. It runs in front of requests that match, so anything slow you put there is slow for every one of them. Contentful's guide makes the same case for keeping it light: no heavy computation, no blocking operations. I'd add that a database call per request in Proxy is almost always the wrong place for it.

Passing headers upstream

If you want to hand extra request headers to your app, use NextResponse.next({ request: { headers } }). Be precise here. Passing { headers } at the top level sends them to the client instead, which is rarely what you meant. And keep them small, because of the 431 risk above.

Common mistakes

  • No matcher at all. Proxy runs on static assets and images. Add one.
  • Renaming the file, not the export. middleware.ts renamed to proxy.ts with export function middleware inside is a quiet failure. The file must export a single function, default or named proxy.
  • Keeping both files. One source says a leftover is ignored, another says the build fails. Delete the old one.
  • Setting `runtime` in the config. It throws in Proxy. If you need Edge, you're on the deprecated file.
  • Treating Proxy as the auth boundary. Check sessions in Server Functions and the data layer.
  • Building the matcher dynamically. Variables are ignored.
  • Reading internal headers. Don't depend on rsc or next-router-state-tree inside Proxy; they're stripped.
  • Pinning tests to the old helper name. The current docs show unstable_doesProxyMatch , but one author found the 16.4.5 package they installed still exported only unstable_doesMiddlewareMatch from next/experimental/testing/server. Check what your installed version exports before you rewrite imports.
  • Piling on logic. Auth0's framing holds: lightweight routing layer, not business logic.

FAQ

Can I have more than one proxy file?

No. The file must export a single function, default or named proxy, and multiple proxies from the same file aren't supported. If you have several concerns, write small helper functions and call them in order from that one export, returning early when one produces a response.

How do I run background work after the response?

The second argument is a NextFetchEvent , which exposes waitUntil(promise). It keeps the invocation alive until the promise settles, so logging or analytics can finish after the response goes out. Declare only the arguments you use.

Does proxy.ts only work with the App Router?

No. The docs place the file at the project root, or in src , at the same level as pages or app. That covers both routers.

What if I customised pageExtensions?

Name the file to match. With .page.ts as your extension, the docs say to use proxy.page.ts (or proxy.page.js).

The single most useful fact: proxy.ts is middleware.ts renamed, with the same logic, a proxy export and a Node.js runtime you can't configure. The sharpest caveat is just as practical. A matcher gap or a moved Server Function can remove Proxy coverage without any warning, so keep the real authorisation checks next to the data.

this post in the tree

Need this done, not just read?

Discuss your website Book 30 minutes