Next.js 16 renamed middleware.ts to proxy.ts, and the rename is one codemod. The real work is deciding what is allowed to stay in the file.
Here's why it matters: Proxy runs before every matched request, not every page. A database lookup in there adds its round trip to the first byte of every page, every prefetch and, without a matcher, every CSS file and image.
This post covers:
- The rename.
- Where Proxy sits in a request.
- What belongs in it (decisions the request can answer on its own).
- The matcher that keeps it off your assets.
- What to move out first.
Rename middleware.ts to proxy.ts with one codemod
Next.js 16 deprecated the middleware file convention and renamed it to proxy. The file convention docs give the codemod:
npx @next/codemod@canary middleware-to-proxy .It renames middleware.ts to proxy.ts and the exported function from middleware to proxy.
The file still sits in the project root, or in src if you use one, at the same level as app. You still get one per project; split logic into modules and import them.
The reason given for the new name is the useful part. "Middleware" made people think of Express, where you stack handlers freely.
The docs now say outright that this feature "is recommended to be used as a last resort". A proxy is a network boundary in front of your app, and I think that framing should change what you put in it.
The other change: Proxy now defaults to the Node.js runtime, and setting runtime in the file throws an error. Node.js support for Middleware went stable in 15.5.0; 16 made it the default.
So Node APIs work. That does not make it a good place for heavy work, because it still runs before anything renders.
Where Proxy runs in a Next.js request
The docs list the order. Proxy runs after the config-level headers and redirects, and before Next.js even looks at your file system:
- 1next.config headersthen config redirects
- 2proxy.tsrewrite, redirect, headers, or respond
- 3beforeFiles rewritesfrom next.config
- 4Filesystem routespublic/, _next/static/, app/
- 5Dynamic routeslike /blog/[slug]
- 6Fallback rewritesfrom next.config
Whatever Proxy costs, every matched request pays before your page starts. A 40 ms database round trip in there is 40 ms on the first byte of every page, every prefetch and, without a matcher, every asset.
Keep proxy.ts to decisions the request can answer
The getting started guide lists the cases it is for:
- Modifying headers.
- Rewriting for A/B tests.
- Redirects based on the request.
It also says, plainly, that Proxy "is not intended for slow data fetching" and should not be "a full session management or authorization solution".
My rule follows from that:
- If the answer is already in the request (a cookie, a header, the path, a query string), Proxy can act on it.
- If the answer needs a network call, it belongs in the page.
import { NextResponse, type NextRequest } from "next/server";
const LOCALES = ["en", "hi"];
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
// Optimistic auth: is there a session cookie at all? The page verifies it properly.
if (pathname.startsWith("/dashboard") && !request.cookies.has("session")) {
const login = new URL("/login", request.url);
login.searchParams.set("next", pathname);
return NextResponse.redirect(login);
}
// Locale: redirect a bare path once, from the header the browser already sent.
const hasLocale = LOCALES.some((l) => pathname === `/${l}` || pathname.startsWith(`/${l}/`));
if (!hasLocale && !pathname.startsWith("/dashboard")) {
const lang = request.headers.get("accept-language")?.startsWith("hi") ? "hi" : "en";
return NextResponse.redirect(new URL(`/${lang}${pathname}`, request.url));
}
// A/B: a sticky cookie decides the bucket; the rewrite keeps the URL the same.
if (pathname === "/en/pricing" && request.cookies.get("ab-pricing")?.value === "b") {
return NextResponse.rewrite(new URL("/en/pricing-b", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)"],
};Nothing in it waits on anything. Each branch reads the request and returns, which is the whole test I apply to a line in this file.
For geo, note that request.geo and request.ip were removed from NextRequest back in Next.js 15, because the values come from your host.
On Vercel the docs point to geolocation() from @vercel/functions. Elsewhere, read whatever header your CDN sets.
I would add one more rule of my own: no await that leaves the process. A cookie read is fine; a call to Redis or Postgres is not.
And for a plain redirect with no logic, I would skip Proxy entirely. The redirects option in next.config.ts runs earlier in the chain and costs no code.
Add a matcher so Proxy skips static assets
The docs say it directly: without a matcher, Proxy runs on every request, "including static files (_next/static), image optimizations (_next/image), and assets in the public/ folder", and auth logic or redirects "can unintentionally block CSS, JS, or images from loading".
The result? An expired-cookie check redirects the stylesheet request to /login, the browser gets HTML where it expected CSS, and the login page loads without styles.
The negative lookahead in the config above is the docs' own pattern. Two details are easy to miss:
- Matcher values must be constants, because they are read at build time; a variable is ignored.
_next/dataroutes still reach Proxy even if you exclude them, on purpose, so a protected page cannot leak through its data route.
Move these out of Proxy, in order
- The session lookup goes first, and I would not wait for a bug to move it. Proxy keeps the cheap cookie check, and the real verification happens where the data is read: in the page, the route handler, or the Server Function.
The docs make a sharper point about Server Functions. They are POST requests to the page that uses them, so a matcher change can silently drop Proxy coverage. Check auth inside each one regardless.
My Next.js 16 notes cover the other half of this: auth that leans on shared modules or globals in the proxy file breaks, because it may run apart from your render code.
- The feature-flag fetch goes next. Fetch caching options (
cache,next.revalidate,next.tags) have no effect in Proxy, so that fetch hits the network on every request.
Read the flag in a Server Component where caching works, as covered in the App Router caching post.
- Logging can stay, and I would keep it, as long as it does not block. The
event.waitUntil()method keeps the invocation alive until a promise settles, so the response goes out first.
Conclusion
Run the codemod, then read proxy.ts top to bottom and ask one question of every line: does this need to happen before routing, for every request? Keep cookie checks, redirects, rewrites and headers. Move database calls and fetches into the page.
A proxy.ts you need to scroll is a design smell; mine end up around forty lines with a matcher. For the work that does belong in your pages, the Next.js performance guide is the next read.
What is the heaviest thing running in your middleware file today?