Implementing Request Interception with Vercel Edge Middleware
Learn how to use Vercel Edge Middleware to reduce TTFB by intercepting requests at the network edge for geolocation, authentication, and dynamic routing.
04 Jul 2025, 18:28 UTC

The Latency Gap in Serverless Routing
When using standard Serverless Functions, every request—including those that only require a simple redirect or an authentication check—must travel to the region where your function is deployed. This adds unnecessary round-trip time (RTT) and increases Time-to-First-Byte (TTFB).
The solution is Edge Middleware. By executing logic in the Vercel Edge Runtime (a lightweight V8 engine) at the network edge, you can intercept requests before they ever reach your origin server or cache. This allows you to handle geolocation, A/B testing, and authentication checks in milliseconds, regardless of where the user is located.
Runtime Constraints and Compatibility
Because the Edge Runtime is not a full Node.js environment, you cannot use Node-specific APIs. This is a critical architectural distinction that affects which libraries you can import.
| Feature | Edge Runtime | Node.js Serverless |
|---|---|---|
| Standard Web APIs | Supported (Request, Response, Fetch) | Supported (via polyfills/Node) |
| Node.js Modules | Unsupported (no fs, path, crypto) |
Fully Supported |
| Execution Limit | Strict/Short (Optimized for low latency) | Higher (Optimized for heavy compute) |
| Cold Starts | Near-Zero | Variable |
Implementing a Global Request Interceptor
To implement middleware, you must place a middleware.ts (or .js) file in the root of your project or inside the src directory. Vercel automatically detects this file and deploys it to the Edge Network.
Example: Geolocation-based Redirect
In this scenario, we intercept requests to the homepage and redirect users based on their country code provided by the Vercel Edge headers.
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
// Extract country from Vercel's edge headers
const country = request.geo?.country || 'US';
// Only intercept the root path to avoid infinite loops
if (request.nextUrl.pathname === '/') {
if (country === 'GB') {
return NextResponse.redirect(new URL('/uk', request.url));
}
}
return NextResponse.next();
}
Controlling Execution with Matchers
Running middleware on every single asset (images, CSS, JS) adds unnecessary overhead. Use a matcher config to limit the middleware to specific paths.
// middleware.ts (continued)
export const config = {
matcher: [
/*
* Match all request paths except for the following:
* 1. /api (API routes)
* 2. /_next/static (static files)
* 3. /_next/image (image optimization files)
* 4. /favicon.ico (favicon file)
*/
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
};
Deployment and Verification
Deploy the code to your Vercel project using your standard CI/CD pipeline (e.g., git push). To verify the middleware is executing at the edge rather than the serverless origin, follow these steps:
- Open your browser's Developer Tools and navigate to the Network tab.
- Refresh the page and select the primary document request.
- Inspect the Response Headers. Look for
x-vercel-cache. While this primarily indicates cache status, the speed of the redirect (visible in the Timing tab) will confirm edge execution if the RTT is significantly lower than your origin region's latency. - Check the Vercel Project Logs in the dashboard. Filter by the "Edge" runtime to ensure the requests are being processed by the Edge function and not the Serverless function.
Recovery and Rollback
Because middleware intercepts all traffic, a logic error (such as an incorrect redirect loop) can make your entire site inaccessible. To recover:
- Immediate Rollback: Use the Vercel Dashboard to "Instant Rollback" to the last known stable deployment. This reverts the
middleware.tsfile to its previous state. - Emergency Bypass: If you cannot access the dashboard, remove the
middleware.tsfile from your repository and push the change to trigger a redeploy without the interceptor.
Limitations
Edge Functions have a strict bundle size limit. Avoid importing large libraries (like heavy SDKs or complex validation schemas) directly into the middleware. If you need to perform a heavy database query, use the middleware to validate a session token and then pass the request to a standard Serverless Function for the heavy lifting.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.