A Route Handler or a page starts working once the request already has a destination. Some decisions are better made earlier: an old address should lead to the new one, every response should carry an identifier, nobody should reach the pages during maintenance. And there's one we've been carrying since 02-04: returning a real 404 when an event doesn't exist, which is impossible once the shell has been sent.
For this, Next.js offers proxy.ts, a single file that runs in front of the routes. It's powerful, and that's precisely why you should use it sparingly: every millisecond it spends is paid for by the whole site, and every error in it breaks the whole site. In this lesson you'll see what it can do, what isn't its job and when configuration is enough.
- The file
proxy.ts lives at the project root, at the same level as app/. It exports a function called proxy and, optionally, a config object:
// proxy.ts — first version, to see how it works
import { type NextRequest, NextResponse } from 'next/server'
export function proxy(request: NextRequest) {
console.log(request.method, request.nextUrl.pathname)
return NextResponse.next()
}Start the server, open the home page and look at the terminal: there are dozens of lines. With no further instructions, the function runs on every request, including JavaScript, images and link prefetches.
What it returns decides what happens:
| Returns | Effect |
|---|---|
Nothing, or NextResponse.next() |
The request continues on its way |
NextResponse.next({ request: { headers } }) |
It continues, with different request headers |
NextResponse.redirect(url, 308) |
The browser requests another address |
NextResponse.rewrite(url) |
Another route is served without changing the visible address |
new Response(…) or Response.json(…) |
The proxy answers; the route doesn't run |
There can only be one file, but nothing stops you from splitting its code into modules and importing them. The second argument, which we won't use, provides waitUntil for background work; you can also call after, which we'll see in 07-04.
- When it runs
flowchart TD
P["Request"] --> H["1. headers from next.config"]
H --> R["2. redirects from next.config"]
R --> X["3. proxy.ts"]
X --> B["4. beforeFiles rewrites"]
B --> F["5. Files and static routes<br/>public, _next/static, app"]
F --> A["6. afterFiles rewrites"]
A --> D["7. Dynamic routes<br/>/events/[slug]"]
D --> L["8. fallback rewrites"]
Two consequences. A redirect in next.config.ts is resolved before reaching the proxy. And the proxy runs before knowing which route will handle the request: it has no params, only the address.
It runs on Node.js, and that isn't configurable: exporting runtime from this file is an error. It can use Node APIs, but the documentation asks you to treat it as if it were running somewhere else, because a platform may deploy it on its content delivery network:
- Don't share state with the application through module variables or
globalThis. It communicates with it through headers, cookies, the URL or rewrites. - Directives have no effect: neither
'use cache'nor'use server'. Alib/data/function with'use cache', called from here, would query every time. fetchcache options don't store anything either.
Server Actions aren't separate routes: they arrive as a POST to the page where they're used. If the proxy handles that page, it also handles its actions; if you exclude the page, you exclude them too.
- The matcher
config.matcher says which routes it runs for. It's the first optimization and the most effective one, because whatever doesn't match never even gets in:
| Pattern | Matches |
|---|---|
/events/:slug |
/events/a, but not /events/a/b |
/dashboard/:path* |
Zero or more segments |
/dashboard/:path+ |
One or more |
/((?!_next/).*) |
Everything except what starts with _next/ |
It accepts a list, and objects with source, has and missing to require or exclude headers, cookies or parameters. The values are analyzed at build time: they must be literals, and a variable is ignored.
Ours will be broad, because we want to identify every page and API request:
export const config = {
matcher: [
{
source: '/((?!_next/|images/|favicon.ico|robots.txt|sitemap.xml).*)',
missing: [
{ type: 'header', key: 'next-router-prefetch' },
{ type: 'header', key: 'purpose', value: 'prefetch' },
],
},
],
}Built assets, posters, metadata files and prefetches are excluded. A page with twenty visible links shouldn't run this code twenty times for visits that may never happen.
- Redirects: here or in the configuration?
The guide's previous website used /whats-on/jazz-night. The mapping is fixed and known in advance, so it doesn't need code:
// next.config.ts (addition)
async redirects() {
return [
{ source: '/whats-on', destination: '/events', permanent: true },
{ source: '/whats-on/:slug', destination: '/events/:slug', permanent: true },
{ source: '/halls/:slug', destination: '/venues/:slug', permanent: false },
]
},permanent: true responds with 308, which browsers and search engines remember indefinitely; false, with 307. Both keep the method, unlike the classic 301 and 302. Start with temporary ones: a wrong permanent redirect can't be withdrawn from the browsers that have already seen it. URL parameters are kept.
| Mechanism | When | Code |
|---|---|---|
redirects in next.config.ts |
The rule depends only on the path, or on a specific header, cookie or parameter | 307 or 308 |
NextResponse.redirect in the proxy |
Something has to be computed from the request | Whichever you choose |
redirect in a Server Component |
It depends on data; after the shell there's no HTTP status (02-03) | 307 or a meta tag |
redirect in a Server Action |
After writing | 303 |
redirect in a Route Handler |
Short links, returns from third parties | 307 |
Configuration redirects are fixed at build time. If there are thousands of them or they change every day, the alternative is a fast key-value store queried from the proxy.
One case that does need code: someone printed posters with /events/Jazz-Night. Slugs are always lowercase, and lowercasing a string can't be expressed with a pattern. We'll include it in the final version.
- Headers
When someone says "I got an error", it helps to be able to find their request in the logs. An identifier per request makes that possible: it's generated on the way in, passed to the application and returned to the browser.
// lib/proxy/request-id.ts
import { type NextRequest, NextResponse } from 'next/server'
export const REQUEST_ID_HEADER = 'x-request-id'
export function continueWithId(request: NextRequest): NextResponse {
const id = crypto.randomUUID()
const headers = new Headers(request.headers)
headers.set(REQUEST_ID_HEADER, id) // Replaces whatever the client sent
const response = NextResponse.next({ request: { headers } })
response.headers.set(REQUEST_ID_HEADER, id)
return response
}There are two directions, and they're easy to mix up:
NextResponse.next({ request: { headers } })changes the headers your application receives.response.headers.set(…), orNextResponse.next({ headers }), adds headers to what the browser receives. Copying the request headers there would publish the cookies and whatever your infrastructure had added.
It uses set rather than "create it if it's missing": a header the application considers its own must never be able to come from outside. With an identifier, that's a nuisance in the logs; with something like x-user, it would be impersonation. That's also why we won't pass identities this way in module 8.
In a Route Handler it's read with request.headers.get(REQUEST_ID_HEADER); in a Server Component, with await headers(), which leaves that part out of the shell. It'll be put to use in 10-05.
For headers that are the same on every response, you don't need code: the headers option in next.config.ts is cheaper. Security headers are covered in 08-05.
- Rewrites and cookies
A rewrite serves a different route from the one shown in the address bar. It's used for tests with two versions, multi-tenant sites or gradual migrations. This example splits visits between two home pages and remembers the choice:
// Example only: not part of the project
export function proxy(request: NextRequest) {
if (request.nextUrl.pathname !== '/') return NextResponse.next()
const remembered = request.cookies.get('home')?.value
const variant =
remembered === 'a' || remembered === 'b' ? remembered : Math.random() < 0.5 ? 'a' : 'b'
const response =
variant === 'b'
? NextResponse.rewrite(new URL('/home-b', request.url))
: NextResponse.next()
response.cookies.set('home', variant, {
httpOnly: true,
sameSite: 'lax',
path: '/',
maxAge: 60 * 60 * 24 * 30,
})
return response
}The interesting part is what doesn't happen: neither home page reads the cookie, so both stay prerendered. The dynamic decision is outside them.
- Cookies are read from the request and written to the response, which is a different object.
- The value is checked. Anyone can edit a cookie.
/home-bcan still be visited, so it's a good idea to mark it as non-indexable.revalidatePathworks with the destination, not with the visible address (05-04).- Don't rewrite with
fetch:NextResponse.rewritepropagates the headers client-side navigation needs.
If the rule is fixed, there's rewrites in next.config.ts.
- A real 404
The page for an event that doesn't exist shows the right content with a 200 and noindex. For the status to be 404, the decision has to be made before the shell. The check happens on every visit to an event page, so it has to be cheap. We have two filters:
- The shape. One of our slugs only has lowercase letters, digits and hyphens.
/events/wp-login.phpis discarded without asking anyone. - Existence. Here something has to be queried.
| How to query | Advantage | Drawback |
|---|---|---|
| Direct query to PostgreSQL | No middlemen | One query per visit, because 'use cache' doesn't work here; another pool |
| In-memory list in the proxy | Instant | No guarantee the memory is kept, and no way to invalidate it |
| External store (Redis or similar) | Fast and shared | Another piece to keep in sync |
| Our own Route Handler, with the cached function | Reuses the cache and its tags | An HTTP hop inside the house |
In 04-01 we said the server shouldn't call its own Route Handlers. The reason was that it could call the function directly, and here it can't without losing the cache. The documentation uses this same pattern in its redirects guide. We choose the last row.
// app/api/events/[slug]/exists/route.ts
import { getEventBySlug } from '@/lib/data/events'
export async function GET(
_request: Request,
{ params }: RouteContext<'/api/events/[slug]/exists'>,
) {
const { slug } = await params
const event = await getEventBySlug(slug) // Cached, with the event:slug tag
return new Response(null, {
status: event ? 204 : 404,
headers: { 'Cache-Control': 'no-store' },
})
}// lib/proxy/events.ts
import { SITE_URL } from '@/lib/site'
const SLUG_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
const MAX_LENGTH = 140
const TIMEOUT_MS = 800
export function isPossibleSlug(slug: string): boolean {
return slug.length <= MAX_LENGTH && SLUG_SHAPE.test(slug)
}
// When in doubt, it returns true: the page knows how to handle a missing event
export async function eventExists(slug: string): Promise<boolean> {
const origin = process.env.INTERNAL_URL || SITE_URL
try {
const response = await fetch(new URL(`/api/events/${slug}/exists`, origin), {
signal: AbortSignal.timeout(TIMEOUT_MS),
redirect: 'error',
})
return response.status !== 404
} catch (error) {
console.error('The proxy could not check an event:', error)
return true
}
}- It fails toward the harmless option. If the endpoint is slow or goes down, the visit continues and you get the previous behavior. An accessory check mustn't prevent anyone from seeing an event that exists.
- The origin is configuration, not
request.nextUrl.origin. That value can come from theHostheader, which is written by the caller: a server that accepts anyHostwould end up sending requests wherever a stranger wants.INTERNAL_URLalso lets you stay off the public network; in development,SITE_URLis enough. AddINTERNAL_URLandMAINTENANCE_MODEto.env.example. They're read fromprocess.env, withoutreadEnv, so the proxy doesn't load the application's configuration. slughas already gone throughisPossibleSlug, so it can't alter the path.- Invalidation is already taken care of. When an event is published,
invalidateEventexpiresevent:slug, and with it any negative response that might have been stored.
7.1. The complete file
// proxy.ts
import { type NextRequest, NextResponse } from 'next/server'
import { isPossibleSlug, eventExists } from '@/lib/proxy/events'
import { continueWithId } from '@/lib/proxy/request-id'
const NO_PAGE_PATH = '/no-page-path' // No route matches it
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl
if (process.env.MAINTENANCE_MODE === '1') return maintenanceResponse(pathname)
const slug = /^\/events\/([^/]+)$/.exec(pathname)?.[1]
if (slug !== undefined) {
const lowercase = slug.toLowerCase()
if (slug !== lowercase && isPossibleSlug(lowercase)) {
const destination = request.nextUrl.clone()
destination.pathname = `/events/${lowercase}`
return NextResponse.redirect(destination, 308)
}
if (!isPossibleSlug(slug) || !(await eventExists(slug))) {
return NextResponse.rewrite(new URL(NO_PAGE_PATH, request.url))
}
}
return continueWithId(request)
}
function maintenanceResponse(pathname: string): Response {
const headers = { 'Retry-After': '600', 'Cache-Control': 'no-store' }
if (pathname.startsWith('/api/')) {
const error = { code: 'unavailable', message: 'Please try again later.' }
return Response.json({ error }, { status: 503, headers })
}
return new Response(
'<!doctype html><html lang="en"><meta charset="utf-8"><title>AgendaViva</title>' +
"<h1>We'll be right back</h1><p>We're carrying out some maintenance.</p></html>",
{ status: 503, headers: { ...headers, 'Content-Type': 'text/html; charset=utf-8' } },
)
}
export const config = {
matcher: [
{
source: '/((?!_next/|images/|favicon.ico|robots.txt|sitemap.xml).*)',
missing: [
{ type: 'header', key: 'next-router-prefetch' },
{ type: 'header', key: 'purpose', value: 'prefetch' },
],
},
],
}Rewriting to a route that doesn't exist makes Next.js serve app/not-found.tsx with its 404 status. That page is prerendered: answering a bot that tries a thousand names costs very little. You lose the specific text from events/[slug]/not-found.tsx, which is left for the cases where the proxy lets the request through: when the check doesn't answer in time, or when the event is withdrawn between the check and the render. If you wanted to keep it, you'd rewrite to a page of your own that calls notFound() when it's prerendered.
Maintenance answers from the proxy without running anything else. It's a 503 with Retry-After: a 200 would make search engines index the notice. Turning it on requires restarting the process, because it's an environment variable; if you need to do it on the fly, the load balancer is usually a better place.
The existence check doesn't loop back on itself: /api/events/x/exists also goes through here, but it doesn't match the event page expression.
# With npm run build && npm run start
curl -s -o /dev/null -w '%{http_code}\n' localhost:3000/events/jazz-night # 200
curl -s -o /dev/null -w '%{http_code}\n' localhost:3000/events/does-not-exist # 404
curl -s -o /dev/null -w '%{http_code}\n' localhost:3000/events/wp-login.php # 404
curl -s -i localhost:3000/events/Jazz-Night | head -n 3 # 308
curl -s -i localhost:3000/whats-on/jazz-night | head -n 3 # 308
curl -s -i localhost:3000/events | grep -i x-request-idIn development, the first check may use up the 800 ms while the Route Handler is being compiled; you'll see the warning in the terminal and a 200. Try again.
Is it worth it? For people, nothing changes. Whoever looks at status codes gains: search engines, analytics, link checkers, audits. And it costs one internal request per event page load. In a project without that requirement, a 200 with noindex is a reasonable answer.
- What isn't its job
| Temptation | Why not | Where |
|---|---|---|
| All the authorization | A route forgotten in the matcher or an action moved to another page is left unchecked |
Next to the data (08-04) |
| Reading the session from the database | It's paid for on every request to the site | In the page or the data function |
| Loading data to pass it in headers | Headers have a limited size, and going over it causes a 431 | Server Components |
| Rate limiting with an in-memory counter | Each instance has its own | Platform, or shared store (07-03) |
| Transforming the body | It's kept in memory so it can be read twice | Route Handler |
| State in module variables | There's no guarantee it's kept | Cookies, headers, external store |
The first row deserves a closer look. In March 2025 the CVE-2025-29927 vulnerability was published: by sending a certain internal header, an attacker could make the middleware not run. Applications that checked access there, and nowhere else, were left wide open; those that checked again next to the data weren't. It was fixed quickly, and the lesson still holds.
What does make sense is an optimistic check: if there isn't even a session cookie, send the person to /sign-in without rendering the dashboard. It saves work and improves the experience, but it isn't what protects anything. We'll add it in 08-04.
About the fifth row: when there's a proxy, Next.js keeps the body in memory so both it and the route can read it, up to 10 MB by default; anything beyond that is truncated. Our 2 MB uploads fit. The option that changes it, proxyClientMaxBodySize, is still experimental.
And a general rule: an uncaught exception in the proxy affects every route in the matcher. Here, everything that can fail is caught.
- If you're coming from middleware.ts
Up to version 15, this file was called middleware.ts. The function is the same; the name changed to avoid confusion with other frameworks' middleware and to make it clear that it's a network boundary, meant as a last resort.
middleware.ts |
proxy.ts |
|
|---|---|---|
| Status in 16 | Deprecated | The current one |
| Function | middleware |
proxy |
| Runtime | Edge by default | Node.js, not configurable |
| URL option | skipMiddlewareUrlNormalize |
skipProxyUrlNormalize |
matcher, NextRequest, NextResponse |
Same | Same |
The tool renames the file and the function. Afterwards, remove export const config = { runtime: … } if it was there, because it's now an error. If you depend on the Edge runtime, for now you have to keep middleware.ts: proxy.ts doesn't support it. In return, on Node.js that runtime's restrictions disappear, and with them many alternative libraries that were used only to work around them.
Common Mistakes and Tips
- Not setting a
matcher. The proxy also runs for JavaScript and images, and a redirect can leave the page without styles. - Building the
matcherwith variables. It's ignored. - A redirect loop: redirecting to
/sign-inwithout excluding/sign-in. - Using it as the only access barrier.
- Calling functions with
'use cache'and expecting them to store anything. - Copying the request headers into the response.
- Trusting a header of your own without replacing whatever arrives from outside.
- Permanent redirects that haven't been tested as temporary ones.
- Querying with no time limit, or blocking the visit if the query fails.
- Writing code for what
redirectsorheadersin the configuration already solve. - Creating
proxy.tsinsideapp/. It goes at the root.
Exercises
Exercise 1: choosing the place
Say where you'd handle each of these: (a) /contact becomes /help; (b) after creating an event, going back to the list; (c) whoever reaches /dashboard without a session cookie goes to /sign-in; (d) an organizer can only edit their own events; (e) X-Content-Type-Options: nosniff on every response; (f) a visitor with the cookie lang=es sees /es when opening /; (g) each venue will have a subdomain with its own guide.
Solution
- (a)
redirectsinnext.config.ts. - (b)
redirectin the Server Action. - (c) Proxy, as an optimistic check, and a real check in the page and in the data.
- (d) In the data function, with the owner in the
where. The proxy doesn't know who owns an event. - (e)
headersinnext.config.ts. - (f) It can be done in
redirectswith a cookie-typehas. If it has to be combined withAccept-Language, proxy (09-05). - (g) Proxy: it reads the subdomain, validates it and rewrites to
/venues/[slug]. The visible address is kept.
Exercise 2: reviewing a proxy
Find at least five problems and write a correct version.
const PROTECTED = ['/dashboard/:path*', '/admin/:path*']
let visits = 0
export async function proxy(request: NextRequest) {
visits++
const id = request.cookies.get('session')?.value
const user = await findUserBySession(id)
if (!user) return NextResponse.redirect(new URL('/dashboard/sign-in', request.url), 308)
const headers = new Headers(request.headers)
headers.set('x-user', user.id)
return NextResponse.next({ headers })
}
export const config = { matcher: PROTECTED }Solution
- The
matcheris a variable: it's ignored. /dashboard/sign-inis inside the protected area: a redirect loop.- The 308 is remembered: even with a session, the browser would keep going to the sign-in page.
- It queries the database on every request, without catching errors.
- It sends all the request headers to the browser, cookies included.
- It passes the identity in a header.
visitsdoesn't count anything reliable.
// Example only: the project's version is written in 08-04
export function proxy(request: NextRequest) {
if (request.cookies.has('session')) return NextResponse.next()
const destination = new URL('/sign-in', request.url)
destination.searchParams.set('returnTo', request.nextUrl.pathname)
return NextResponse.redirect(destination, 307)
}
export const config = { matcher: ['/dashboard/:path*', '/admin/:path*'] }It only checks whether the cookie exists. Anyone who makes one up will get past this point and be stopped at the real check, next to the data.
Exercise 3: changing domains
The guide has moved from old.agendaviva.example to agendaviva.example; both names point to the same server. Redirect while keeping the path and parameters, without touching proxy.ts. What would you do if, on top of that, the old event pages used a number, /event/123, and there were 8,000 of them?
Solution
// next.config.ts, inside redirects()
{
source: '/:path*',
has: [{ type: 'host', value: 'old.agendaviva.example' }],
destination: 'https://agendaviva.example/:path*',
permanent: true,
},Parameters are kept on their own. If there's a load balancer or CDN in front, it's even better to do it there: the request never reaches Node.
For the 8,000 event pages, a list in the configuration would be huge. Two options: a redirects table queried by a Route Handler in app/event/[number]/route.ts, which calls permanentRedirect, or a key-value store queried from the proxy. The first is enough, because /event/… is a space of its own that nothing else uses: there's nothing to intercept.
Conclusion
proxy.ts is a function in front of every route that redirects, rewrites, changes headers or answers directly. The matcher limits its cost; Next.js configuration handles fixed rules without code, and anything slow or important stays further in: data in its functions, authorization next to it. It runs on Node.js, with no cache and no shared state, and it replaces the old middleware.ts. AgendaViva now identifies every request, normalizes addresses, can be put into maintenance mode and returns real 404s, a promise outstanding since module 2.
Until now, whoever calls asks for something and waits. Some programs do the opposite: they report that something has happened, and you have to decide whether to believe them. In Webhooks and External API Integration, the venues will tell us about capacity changes, and AgendaViva will also learn to talk to a third-party service that doesn't always answer.
