Routing Middleware
Routing Middleware is available on all plans
Routing Middleware executes code before a request is processed on a site, and are built on top of fluid compute. Based on the request, you can modify the response.
Because it runs globally before the cache, Routing Middleware is an effective way of providing personalization to statically generated content. Depending on the incoming request, you can execute custom logic, rewrite, redirect, add headers and more, before returning a response.
Routing Middleware configured with the proxy property runs on the Node.js runtime. With the middleware.ts file convention, the default is Edge. See runtime options for information on how to change the runtime of your Routing Middleware.
You can use Routing Middleware with any framework. To add a Routing Middleware to your app, point the proxy property in vercel.json at your entrypoint:
{
"$schema": "https://openapi.vercel.sh/vercel.json",
"proxy": {
"entrypoint": "proxy.ts"
}
}Your entrypoint exports the handler as a default export:
export default function proxy(request: Request) {
const url = new URL(request.url);
// Redirect old paths
if (url.pathname === '/old-page') {
return new Response(null, {
status: 302,
headers: { Location: '/new-page' },
});
}
// Continue to next handler
return new Response('Hello from your Middleware!');
}export default function proxy(request) {
const url = new URL(request.url);
// Redirect old paths
if (url.pathname === '/old-page') {
return new Response(null, {
status: 302,
headers: { Location: '/new-page' },
});
}
// Continue to next handler
return new Response('Hello from your Middleware!');
}The entrypoint can live in a subdirectory, such as src/proxy.ts. Add proxy.matcher to limit which paths run your Routing Middleware.
You can also create a middleware.ts file at your project's root directory and skip vercel.json:
export default function middleware(request: Request) {
return new Response('Hello from your Middleware!');
}
export const config = {
runtime: 'nodejs',
};export default function middleware(request) {
return new Response('Hello from your Middleware!');
}
export const config = {
runtime: 'nodejs',
};Routing Middleware has full support for the console API, including time, debug, timeEnd. Logs will appear inside your Vercel project by clicking View Functions Logs next to the deployment.
If your Routing Middleware depends on a database far away from one of our supported regions, the overall latency of API requests could be slower than expected, due to network latency while connecting to the database from an edge region. To avoid this issue, use a global database. Vercel has multiple global storage products, including Global Config and Vercel Blob. You can also explore the storage category of the Vercel Marketplace to learn which option is best for you.
The following limits apply to requests processed by Routing Middleware:
Routing Middleware is available on the Node.js, Bun, and Edge runtimes. An entrypoint set through the proxy property runs on Node.js.
With the middleware.ts file convention, the default runtime is Edge. You can change the runtime to Node.js by exporting a config object with a runtime property in your middleware.ts file.
To use the Bun runtime, set bunVersion in your vercel.json file and your runtime config to nodejs.
export const config = {
runtime: 'nodejs', // or 'edge' (default)
};
export default function middleware(request: Request) {
// Your middleware logic here
return new Response('Hello from your Middleware!');
}export const config = {
runtime: 'nodejs' // or 'edge' (default)
}
export default function middleware(request: Request) {
// Your middleware logic here
return new Response('Hello from your Middleware!');
}Routing Middleware is priced using the fluid compute model, which means you are charged by the amount of compute resources used by your Routing Middleware. See the fluid compute pricing documentation for more information.
The Vercel Observability dashboard provides visibility into your routing middleware usage, including invocation counts and performance metrics. You can get more insights with Observability Plus:
- Analyze invocations by request path
- Break down actions by type, such as redirects or rewrites
- View rewrite targets and frequency
- Use the query builder for custom insights
Learn more about Routing Middleware by exploring the following resources:
Was this helpful?
middleware.tsexport default function proxy(request: Request) {
const url = new URL(request.url);
// Redirect old paths
if (url.pathname === '/old-page') {
return new Response(null, {
status: 302,
headers: { Location: '/new-page' },
});
}
// Continue to next handler
return new Response('Hello from your Middleware!');
}middleware.tsexport default function middleware(request: Request) {
return new Response('Hello from your Middleware!');
}
export const config = {
runtime: 'nodejs',
};middleware.tsmiddleware.tsCross-link map: Routing Middleware (/docs/routing-middleware)
From the Vercel docs graph (built 2026-09-06T06:25:16.735Z), spanning vercel.com docs + KB, nextjs.org, ai-sdk.dev, and other Vercel documentation sites. Full graph as JSON: https://vercel.com/docs/graph.json
Semantically closest pages
- Getting Started with Routing Middleware — Learn how you can use Routing Middleware, code that executes before a request is processed on a site, to provide speed a
- Vercel Edge Middleware: Dynamic at the speed of static (historical)
- Routing — Learn how Vercel's CDN routes requests through firewall, project routes, and deployment routes before reaching your appl
- Routing Middleware API — Learn how you can use Routing Middleware, code that executes before a request is processed on a site, to provide speed a
- Life of a Vercel request: Application-aware routing
This page links to (16)
- Fluid compute — Learn about fluid compute, an execution model for Vercel Functions that provides a more flexible and efficient way to ru
- Frameworks on Vercel — Vercel supports a wide range of the most popular frameworks, optimizing how your application builds and runs no matter w
- Runtimes — Runtimes transform your source code into Functions, which are served by our CDN. Learn about the official runtimes suppo
- Using the Bun Runtime with Vercel Functions — Learn how to use the Bun runtime with Vercel Functions to create fast, efficient functions.
- Edge Runtime — Learn about the Edge runtime, an environment in which Vercel Functions can run.
- Using the Node.js Runtime with Vercel Functions — Learn how to use the Node.js runtime to create functions and deploy Node.js servers on Vercel.
- Fluid compute pricing — Learn about usage and pricing for fluid compute on Vercel.
- Vercel Global Config — A Global Config is a global data store that enables experimentation with feature flags, A/B testing, critical redirects,
- Observability — Find production errors, capture request traces, and discover queryable metrics with Vercel Observability and Vercel CLI.
- Observability Insights — List of available data sources that you can view and monitor with Observability on Vercel.
- Observability Plus — Learn about using Observability Plus and its limits.
- Static Configuration with vercel.json — Learn how to use vercel.json to configure and override the default behavior of Vercel from within your project.
- Global network and regions — View the list of regions supported by Vercel's CDN and learn about our global infrastructure.
- Routing Middleware API — Learn how you can use Routing Middleware, code that executes before a request is processed on a site, to provide speed a
- Getting Started with Routing Middleware — Learn how you can use Routing Middleware, code that executes before a request is processed on a site, to provide speed a
- Vercel Blob — Vercel Blob is a scalable, cost-effective object storage service with private and public access modes for files up to 5
Pages that link here (116)
By site: vercel-changelog (27) · vercel-kb (37) · vercel-web (20) · vercel-docs (32)
From vercel-changelog
- Advanced Remix integration with streaming SSR and multi-runtime support
- Edge Config is now generally available
- Edge Function metrics now available in Monitoring
- Edge Functions are now available in Public Beta
- Edge Functions are now generally available
- Edge Middleware and Edge Functions are now powered by Vercel Functions
- Enhanced geolocation information for Vercel Functions
- Hydrogen 2 projects can now be deployed with zero configuration
- Hydrogen projects can now be deployed with zero configuration
- Improved Node.js compatibility for Edge Middleware and Edge Functions
- Improved performance for Vercel Postgres from Edge Functions
- Improvements and fixes
- Introducing the Runtime Cache API
- IP Geolocation now available for all plans
- Improvements and fixes
- More flexible Environment Variables in Edge Functions and Middleware
- New build and deploy capabilities in Vercel CLI
- New execution duration limit for Edge Functions
- Next.js 13.4 on Vercel
- OpenAI will not support the Hong Kong region (hkg1) for Functions
- Vercel Edge Functions can now be regional or global
- Run scheduled jobs with Vercel Cron Jobs and Vercel Functions
- Support for Remix v2
- Vercel CLI v28 is now available
- Vercel Cron Jobs are now generally available
- Vercel Edge Functions are now in public beta
- Vercel Python SDK is now available in beta
From vercel-kb
- A/B Testing on Vercel — Learn best practices for A/B testing on Vercel
- Adding a response header — Learn how to add a response header in your Middleware.
- Build with an Express starter template — Deploy an Express app to Vercel from a template. Browse Express starters from Vercel and the community, then run them lo
- Build with a FastAPI starter template — Browse FastAPI starter templates for Vercel and deploy one in a few steps. Compare minimal, AI, agent, and full-stack Fa
- Build with a Flask starter template — Deploy a Flask app to Vercel from a starter template. Compare the Flask Hello World starter, AI SDK, alt text generator,
- Build with a Hono starter template — Deploy a Hono app to Vercel from a starter template. Compare the Hono API starter, MCP server, AI SDK, Slack Bolt, Next.
- Can I get a fixed IP address for my Vercel deployments? — Vercel deployments use dynamic IPs by default. Learn how Static IPs, Secure Compute, and AWS PrivateLink give you a fixe
- How to add per-request CSP nonces to CDN-cached HTML on Vercel — Use Routing Middleware and a self-fetch to add a fresh CSP nonce to cached HTML without rendering the page again on ever
- Ensuring safe and effective infrastructure testing — We conduct regular penetration testing through certified third-party assessors to secure the Vercel platform. This guide
- Filtering query parameters — Learn how to filter query parameters in your Middleware.
- How can I increase the limit of redirects or use dynamic redirects on Vercel? — Instructions on how to use Serverless Functions to handle redirects on Vercel.
- How can I allowlist IP addresses for a deployment? — Vercel deployments use dynamic outbound IPs by default. Learn how to allowlist IP addresses for a deployment with Static
- How to enable CORS on Vercel — Learn how to enable CORS on Vercel with vercel.json, Routing Middleware, framework config, and route handlers, plus how
- How to migrate from Fastly to Vercel with zero downtime — Consolidate your CDN infrastructure on Vercel to reduce latency, simplify your configuration, and improve your developer
- How to Optimize Next.js + Sitecore JSS — This guide covers performance and usage considerations when building and deploying your Next.js and Sitecore JSS applica
- How can I make my library compatible with the Vercel Edge Runtime? — Learn how to make your library or SDK compatible with the Edge Runtime for existing Edge Runtime code and Routing Middle
- Migrate a TanStack Start app from Netlify to Vercel — Move your TanStack Start app off Netlify and onto Vercel Functions, where Fluid compute scales it automatically. Swap to
- Migrate to Vercel from Cloudflare — Migrate your website's configuration from Cloudflare Pages or Workers to Vercel
- Migrate to Vercel from Netlify — Migrate your website's configuration from Netlify to Vercel
- Modifying request headers — Learn how to modify request headers in your Middleware.
- Troubleshoot and optimize Active CPU usage on Fluid compute — Diagnose which routes drive Active CPU usage and learn to optimize it. Separate traffic growth from per-request CPU work
- Publish and subscribe to realtime data on Vercel — Learn how to publish and subscribe to realtime data on Vercel with WebSockets, SSE, Redis, and Queues, and when a manage
- Rendering content based on device — Learn how to render different content based on the user agent in your Middleware.
- Can I use SMTP with Vercel? — Vercel Functions can open SMTP connections on the Node.js runtime. Learn which ports are open, why you must await the se
- How to ship an Elysia app on Vercel — Deploy a Elysia app to Vercel with zero configuration. Learn how to ship from a template, the Vercel CLI, or Git, and co
- How to ship an Express app on Vercel — Deploy an Express app to Vercel with zero configuration. Configure response streaming, middleware, cron jobs, the Bun ru
- How to ship a FastAPI app on Vercel — Deploy a FastAPI app to Vercel with zero configuration. Learn how the Python runtime, Vercel Functions, streaming, middl
- How to ship a Fastify app on Vercel — Deploy a Fastify app to Vercel with zero configuration, then add streaming, lifecycle hooks, cron jobs, and observabilit
- How to ship a Flask app on Vercel — Deploy a Flask app to Vercel with zero configuration. Learn how to ship from a template, the Vercel CLI, or Git, and con
- How to ship an H3 app on Vercel — Deploy an H3 app to Vercel with zero configuration. Learn to configure streaming, middleware, cron jobs, the Bun runtime
- How to ship a Hono app on Vercel — Deploy a Hono app to Vercel with zero configuration. Learn how to ship from a template, the Vercel CLI, or Git, and conf
- How to ship a Koa app on Vercel — Deploy a Koa app to Vercel with zero configuration. Learn how to ship from the Vercel CLI or Git, and configure response
- How to ship a NestJS app on Vercel — Deploy a NestJS app to Vercel with zero configuration. Learn how to ship from a template, the Nest CLI, or Git, and conf
- Using the crypto Web API to redirect requests with a unique token — Learn how to use the Crypto Web API in your Middleware.
- Using xmcp with Next.js — Add an MCP server to an existing Next.js app with xmcp. Create typed tools, add authentication, and deploy to Vercel as
- Vercel vs Netlify — A detailed guide to Vercel vs Netlify: runtimes, compute architecture, AI infrastructure, security, and when to choose e
- Vercel vs Northflank — A detailed guide to Vercel vs Northflank: Fluid compute, CDN and caching, security defaults, AI infrastructure, GPU comp
From vercel-web
- Behind the scenes of Vercel's infrastructure: Achieving optimal scalability and performance
- Billions of dollars, billions of requests: Black Friday-Cyber Monday 2024
- Announcing the Build Output API
- Build your own web framework
- Introducing Edge Config: Globally distributed, instant configuration
- Edge Config: Ultra-low latency data at the edge
- Vercel Edge Functions are now generally available
- New features for SvelteKit: Optimize your application with ease
- Introducing support for WebAssembly at the Edge
- Introducing the Vercel AI SDK
- Regional execution for ultra-low latency rendering at the edge
- Releasing safe and cost-efficient blue-green deployments
- The user experience of the Frontend Cloud
- Using SvelteKit 1.0 on Vercel
- Using the latest Next.js 12.3 features on Vercel
- Replacing Google Optimize with the Vercel Edge Network
- Vercel Edge Middleware: Dynamic at the speed of static (historical)
- Vercel Flags: Platform-native feature flags
- Remix without limits (historical)
- How to build zero-CLS A/B tests with Next.js and Vercel Edge Config
From vercel-docs
- Alerts — Get notified when something's wrong with your Vercel projects. Set up alerts through Slack, webhooks, or email so you ca
- vercel dev — Learn how to replicate the Vercel deployment environment locally and test your Vercel Project before deploying using the
- Frameworks on Vercel — Vercel supports a wide range of the most popular frameworks, optimizing how your application builds and runs no matter w
- Elysia on Vercel — Build fast TypeScript backends with Elysia and deploy to Vercel. Learn the project structure, plugins, middleware, and h
- Hono on Vercel — Deploy Hono applications to Vercel with zero configuration. Learn about observability, ISR, and custom build configurati
- Frontends on Vercel — Vercel supports a wide range of the most popular frontend frameworks, optimizing how your application builds and runs no
- Astro on Vercel — Deploy Astro sites to Vercel and configure server-side rendering, ISR, Web Analytics, Image Optimization, and Routing Mi
- Full-stack frameworks on Vercel — Vercel supports a wide range of the most popular backend frameworks, optimizing how your application builds and runs no
- Next.js on Vercel — Vercel is the native Next.js platform, designed to enhance the Next.js experience.
- Supported Frameworks on Vercel — Learn about the frameworks that can be deployed to Vercel.
- Configuring regions for Vercel Functions — Learn how to configure regions for Vercel Functions.
- Using the Bun Runtime with Vercel Functions — Learn how to use the Bun runtime with Vercel Functions to create fast, efficient functions.
- Using WebAssembly \(Wasm\) — Learn how to use WebAssembly \(Wasm\) to enable low-level languages to run on Vercel Functions and Routing Middleware.
- How requests flow through Vercel — Learn how Vercel routes, secures, and serves requests from your users to your application.
- Vercel Global Config — A Global Config is a global data store that enables experimentation with feature flags, A/B testing, critical redirects,
- Getting started with Global Config — Learn how to create a Global Config store and read from it in your project.
- Using Global Config with Statsig — Learn how to use Global Config with Vercel's Statsig integration.
- Incremental Migration to Vercel — Learn how to migrate your app or website to Vercel with minimal risk and high impact.
- Runtime Logs — Learn how to search, inspect, and share your runtime logs with the Logs tab.
- Secure Compute — Secure Compute provides dedicated private networks with VPC peering for Enterprise teams.
- Static IPs — Access IP-restricted backend services through shared static egress IPs for Pro and Enterprise teams.
- Account Plans on Vercel — Learn about the different plans available on Vercel.
- Multi-Project Platforms Quickstart — Programmatically host code for user-generated or AI-generated applications on Vercel.
- Calculating usage of resources — Understand how Vercel measures and calculates your resource usage based on a typical user journey.
- Static Configuration with vercel.json — Learn how to use vercel.json to configure and override the default behavior of Vercel from within your project.
- Programmatic Configuration with vercel.ts — Define your Vercel configuration in vercel.ts with @vercel/config for type-safe routing and build settings.
- Getting Started with Routing Middleware — Learn how you can use Routing Middleware, code that executes before a request is processed on a site, to provide speed a
- Project-Level Routing Rules — Add redirects, rewrites, headers, and status codes to your project from the dashboard or API, without deploying new code
- Redirects — Learn how to use redirects on Vercel to instruct Vercel's platform to redirect incoming requests to a new URL.
- Service bindings — Call one service from another using caller-declared service bindings.
- Vercel Documentation Sitemap — Browse Vercel documentation pages with summaries, prerequisites, and topics.
- Skew Protection — Learn how Vercel's Skew Protection ensures that the client and server stay in sync for any particular deployment.
