Explain Proxy.ts in Next.js v16
Understand what the built-in `proxy.ts` file in Next.js v16 does, how it replaces `middleware.ts`, and how to use it for redirects, rewrites, headers and simple auth checks.
Explain proxy.ts in Next.js v16
Introduction
If you open a fresh Next.js 16 project and read the docs, you will notice that the old middleware.ts file is gone. It has been renamed to proxy.ts. The middleware file convention is deprecated, and proxy is the name going forward.
The rename is mostly about clarity. "Middleware" was easy to confuse with Express-style middleware, and it was often used as a catch-all for too many things. The name proxy makes it clearer that this code sits in front of your app, on the network boundary, and runs before a request is completed.
Important: proxy.ts is not a reverse proxy server like Nginx or Caddy, and it is not something you wire up yourself. It is a file convention that Next.js picks up automatically.
What does proxy.ts do?
Proxy runs on the server before a request is completed. Based on the incoming request, you can:
- Redirect the user to another URL.
- Rewrite the request to a different route, so the URL in the browser stays the same.
- Modify request or response headers and cookies.
- Respond directly without ever reaching a page or route handler.
Typical use cases are redirects, simple authentication and authorization checks, logging, A/B testing, geo or locale routing, and setting security headers.
What changed from middleware.ts?
| Next.js 15 and earlier | Next.js 16 | |
|---|---|---|
| File name | middleware.ts | proxy.ts |
| Exported function | middleware (or default) | proxy (or default) |
| Runtime | Edge by default | Node.js |
runtime config option | Available | Not available, setting it throws an error |
A few more details worth knowing:
- Proxy defaults to the Node.js runtime, so you have access to Node APIs. This is a nice fit for self-hosting.
- The
runtimeoption cannot be set in a proxy file. - The config flag
skipMiddlewareUrlNormalizewas renamed toskipProxyUrlNormalize. - You can still run the old
middleware.tsfor now, but it is deprecated.
Migrating with the codemod
Next.js ships a codemod that renames the file and the exported function for you:
npx @next/codemod@canary middleware-to-proxy .If you prefer doing it by hand, rename middleware.ts to proxy.ts and rename the exported function from middleware to proxy.
Where does the file go?
Put proxy.ts (or .js) in the project root, or inside src if you use a src directory, at the same level as app or pages. There is only one proxy file per project, and it must export a single function, either as a default export or as a named export called proxy.
my-app/
├── app/
├── public/
├── proxy.ts <- here
└── package.json
Note that it does not go inside pages/api or app/api. Those folders are for API routes and route handlers, which are a different thing.
Example 1: Basic redirect
This is the simplest possible proxy. It redirects /about and everything below it to /home.
// proxy.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// This function can be marked `async` if you use `await` inside
export function proxy(request: NextRequest) {
return NextResponse.redirect(new URL('/home', request.url))
}
export const config = {
matcher: '/about/:path*',
}Explanation
proxyfunction: Next.js calls it with aNextRequestfor every request that matches.NextResponse.redirect: Returns a redirect response to the new URL.config.matcher: Limits the proxy to paths matching/about/:path*.
Example 2: Limiting where the proxy runs with matcher
Without a matcher, proxy runs on every request, including static files in _next/static, image optimization requests in _next/image, and assets in public/. That is almost never what you want, so always narrow it down.
// proxy.ts
export const config = {
matcher: [
// Run on everything except API routes, static files,
// image optimization and favicon
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
}You can also pass a simple array of paths:
export const config = {
matcher: ['/about/:path*', '/dashboard/:path*'],
}Matcher paths must start with /, can use named parameters like /about/:path, and support the modifiers * (zero or more), ? (zero or one) and + (one or more).
Example 3: Conditional rewrite
A rewrite serves a different route while keeping the URL in the browser unchanged. Here we send a mobile user agent to a separate mobile version of a page.
// proxy.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
const userAgent = request.headers.get('user-agent') ?? ''
const isMobile = /Mobile|Android|iPhone/i.test(userAgent)
if (isMobile && request.nextUrl.pathname === '/') {
return NextResponse.rewrite(new URL('/mobile', request.url))
}
return NextResponse.next()
}
export const config = {
matcher: '/',
}Explanation
- Reading the request:
request.headersandrequest.nextUrlgive you the headers and the parsed URL. NextResponse.rewrite: Serves/mobilewhile the visitor still sees/.NextResponse.next(): Lets the request continue as normal when no rule applies.
Example 4: Setting headers
You can modify the response headers, for example to add a custom header or a basic security header.
// proxy.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
const response = NextResponse.next()
response.headers.set('X-Frame-Options', 'DENY')
response.headers.set('X-Content-Type-Options', 'nosniff')
return response
}Example 5: Optimistic auth check
A very common use is redirecting visitors who are not logged in. Here we check for a session cookie and send people to /login if it is missing.
// proxy.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
const session = request.cookies.get('session')
if (!session) {
return NextResponse.redirect(new URL('/login', request.url))
}
return NextResponse.next()
}
export const config = {
matcher: '/dashboard/:path*',
}This is only an optimistic check. It looks at the cookie and nothing more. Always verify the session again close to your data, for example in your server components, route handlers or server actions. Do not rely on proxy as your only line of defense.
Example 6: Forwarding requests to another backend
Because the name is proxy, many people expect it to forward requests to another server. You can do that with a rewrite to an external URL, which is handy when you self-host a separate API next to your Next.js app.
// proxy.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
if (request.nextUrl.pathname.startsWith('/backend')) {
const path = request.nextUrl.pathname.replace('/backend', '')
const target = new URL(path + request.nextUrl.search, 'http://192.168.1.50:4000')
return NextResponse.rewrite(target)
}
return NextResponse.next()
}
export const config = {
matcher: '/backend/:path*',
}For simple cases you can also use rewrites in next.config.js. Proxy is the better choice when you need logic, such as checking a cookie or header before forwarding.
Good to know
- Execution order: Headers and redirects from
next.config.jsrun first, then proxy, thenbeforeFilesrewrites, then filesystem routes such aspublic/andapp/, thenafterFilesrewrites, dynamic routes and finallyfallbackrewrites. - Keep it light: Proxy is meant to be invoked separately from your render code, so do not rely on shared modules or globals. Avoid slow data fetching or heavy work here.
- Background work: The second argument,
event, has awaitUntil(promise)method that keeps the invocation alive so logging or analytics can finish after the response is sent. - Custom page extensions: If you changed
pageExtensions(for example to.page.ts), name the fileproxy.page.tsinstead.
Conclusion
In Next.js 16, proxy.ts is the new name for what used to be middleware.ts. It is a single file in your project root that runs on the Node.js runtime before a request is completed, and it lets you redirect, rewrite, set headers, check cookies or respond directly. Combine it with a precise matcher, keep the logic small, and do your real authorization checks closer to your data.
If you are upgrading an existing project, run the middleware-to-proxy codemod and you are most of the way there.