Routing Middleware
Run a function before routing to answer, rewrite or redirect a request, or change its headers, with the same middleware.ts you use on Vercel.
Add middleware
Put a middleware.ts or middleware.js at the project’s root. Its config.matcher says which paths it runs on; without one it runs on every path.
import { next, rewrite, geolocation } from '@vercel/functions'export const config = { matcher: ['/shop/:path*'] }export default function middleware(request: Request) { const { country } = geolocation(request) if (country === 'DE') return rewrite(new URL('/de' + new URL(request.url).pathname, request.url)) return next({ headers: { 'x-from-middleware': '1' } })}The middleware can answer the request itself, let it go on (next()), rewrite it to another path or URL (rewrite()), change its request headers, and add headers and cookies to the answer. ipAddress() and waitUntil() from @vercel/functions work too.
Two other ways to add it: vercel.json’s proxy key ({ "entrypoint": "proxy.ts", "matcher": ["/api/:path*"] }), or a framework’s own middleware (Astro’s edgeMiddleware, Nitro’s vercel-edge, or any Build Output route with middlewarePath).
How it runs
- It’s bundled with esbuild, npm packages included, and runs on Node in the deployment’s own Lambda function. Middleware written for the Edge runtime (
config.runtime: "edge") runs on Node too, as Vercel now runs middleware by default. - It runs after
vercel.json’s redirects and headers, and before the files, rewrites and functions. - It must start answering within its own max duration, or 25 seconds, or the request gets 504
MIDDLEWARE_INVOCATION_TIMEOUT. - A request body over 4.5 MB on its paths gets 413
FUNCTION_PAYLOAD_TOO_LARGE, as on Vercel. - Each call is in the request’s log line: what the middleware did, and how long it took. Observability → Middleware charts it.
Cost
Each request the matcher lets in is a call on the deployment’s Lambda worker, billed as Lambda time like any function request. Paths outside the matcher don’t run it and cost nothing extra. Keep the matcher narrow so static files skip it.
Not supported yet
- Middleware beside a Python API or a single Node server (Express, Nitro’s
node-server): the deploy refuses it for now. It works beside static sites, Node functions inapi/, and framework builds. - Middleware written in Python, and
vercel.json’sskipMiddlewareRequestBody. - A root
middleware.tsin a Next.js project: Next.js brings its own, as on Vercel.