Vercel 09 ▲ Routing Middleware & Skew Protection — Intercepting requests at the edge and preventing version mismatches across deploys
Vercel Middleware allows code to execute before a request is completed, enabling developers to modify the request or response headers, rewrite the path, or redirect the user based on authentication, geolocation, or custom logic. It runs on the Vercel Edge Network, meaning it executes in the region closest to the user, providing ultra-low latency. Because this logic sits between the user and the origin, it is the perfect place to enforce routing rules and manage application state.
Skew Protection, conversely, is a critical feature that manages the “version mismatch” problem. In modern web apps, a user might load the page, but while they are browsing, a new deployment is pushed to production. If the user’s browser attempts to fetch a stale JS bundle or hit a deprecated API route, the application crashes or behaves unpredictably. Vercel’s Skew Protection manages this gap by detecting these version mismatches and forcing a page reload to synchronize the client state with the latest deployment. This chapter explores both the manual implementation of Middleware and the configuration of Skew Protection to ensure seamless deployments.
Key point: Middleware provides a programmable routing layer at the edge for headers, redirects, and rewrites, while Skew Protection is a robust configuration mechanism that detects and mitigates deployment version mismatches by prompting the client to refresh when the edge detects a mismatch between the client’s version and the latest deployment.
The latency problem.
Traditional server-side routing often requires a request to hit the primary origin server, adding unnecessary round-trip time. Middleware solves this by running at the Edge, intercepting the request globally before it ever reaches the compute-heavy origin, making decisions like “redirect to login” or “route to locale” instantaneously.
The authentication bottleneck.
Performing session verification inside every API route or server-side component is repetitive and slow. Middleware exists to centralize this check. By validating a JWT or session cookie at the Edge, the application can reject unauthorized requests before they trigger expensive database or backend processes.
The A/B testing and personalization requirement.
Developers often need to show different content to different users based on headers (like x-vercel-ip-country) or cookies. Middleware makes this trivial by allowing the code to modify the rewrite destination dynamically based on request metadata, enabling sophisticated personalization without modifying the actual file structure.
The deployment skew challenge.
In a continuous deployment environment, the assets (JS/CSS) a user loaded might no longer match the current production backend. If the browser tries to fetch a chunk hash that was deleted in the new deployment, the app breaks. Skew protection exists to automate the detection of this “stale state” and gracefully force the user to reload the page to get the latest bundle.
The edge flexibility trade-off.
Previously, modifying headers or handling redirects required complex vercel.json rules or server-side code. Middleware provides a standard, code-first approach using the Web Request and Response APIs, allowing for complex logic that static configuration files cannot support, while maintaining the performance benefits of Edge functions.
a. Middleware Anatomy and Matching
Middleware resides in a middleware.ts or middleware.js file at the root of the project or inside the src directory. It uses a matcher to determine which paths the middleware executes for. Without a matcher, the middleware executes for every single request, which is usually undesirable because it impacts performance for static assets like images and fonts.
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// Logic here executes for all matched paths
const authCookie = request.cookies.get('token');
if (!authCookie && request.nextUrl.pathname.startsWith('/dashboard')) {
// Redirect unauthenticated users
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*', '/profile/:path*'],
};
The NextRequest object extends the standard Web API Request with Vercel-specific properties like nextUrl, ip, and geo. The NextResponse object allows you to return a redirect, rewrite the path, or set custom headers. The config object is crucial—it defines the scope. Using /:path* ensures that all sub-routes of /dashboard are protected, not just the dashboard root.
b. Request Transformation: Rewrites and Headers
Middleware is most powerful when it transforms requests internally. A “rewrite” changes the destination path without changing the URL the user sees in their browser. This is essential for features like localization or dynamic routing, where the user visits / but receives content from /en-US.
export function middleware(request: NextRequest) {
const country = request.geo?.country || 'US';
if (country === 'GB') {
// Rewrite internally without changing URL
return NextResponse.rewrite(new URL('/uk-content', request.url));
}
// Set a header to pass to the underlying server
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-hello-from-middleware', 'hello');
return NextResponse.next({
request: { headers: requestHeaders },
});
}
This pattern effectively allows the Edge to act as a reverse proxy. By modifying the headers, you pass information from the Edge environment down to your React Server Components or API routes. This is the mechanism used to pass user identity, geolocation, or experiment flags down to the origin code.
c. Skew Protection Configuration
Skew Protection is less about writing code and more about ensuring the application handles deployment boundaries correctly. When enabled, Vercel injects a small piece of logic that monitors the deployment ID. If a user performs a navigation and the server detects that the user is running a version from a previous deployment, Vercel initiates a client-side reload.
// vercel.json
{
"skewProtection": true
}
When skewProtection is true, Vercel uses a special header or cookie mechanism to track the deployment hash. If a user’s client state drifts too far from the current production version, the browser detects the mismatch. This prevents “404 not found” errors on chunk loading, which occur when a browser tries to request a JS file from a deployment that has been purged from the CDN.
Complete Example Session
// ============================================
// PART 1: MIDDLEWARE FILE SETUP
// ============================================
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const url = request.nextUrl;
// ============================================
// PART 2: AUTHENTICATION CHECK
// ============================================
if (url.pathname.startsWith('/admin')) {
const session = request.cookies.get('session');
if (!session) {
return NextResponse.redirect(new URL('/login', request.url));
}
}
// ============================================
// PART 3: DYNAMIC REWRITE
// ============================================
if (url.pathname === '/shop') {
// Serve different content based on a cookie
const region = request.cookies.get('region')?.value || 'US';
return NextResponse.rewrite(new URL(`/shop/${region}`, request.url));
}
return NextResponse.next();
}
// ============================================
// PART 4: MATCHER CONFIGURATION
// ============================================
export const config = {
matcher: ['/admin/:path*', '/shop'],
};
This session demonstrates a standard middleware.ts implementation: it handles authentication for admin routes, performs a dynamic rewrite for shop pages based on region, and restricts execution scope using the matcher configuration.
Quick Reference
Middleware Response Methods
| Method | Description |
|---|---|
NextResponse.next() | Continue to destination |
NextResponse.redirect(url) | HTTP 307/308 redirect |
NextResponse.rewrite(url) | Internal route change |
NextResponse.json(data) | Return JSON directly |
Middleware Request Properties
| Property | Description |
|---|---|
request.nextUrl | Parsed URL object |
request.geo | Geolocation data (country, city) |
request.ip | User’s IP address |
request.cookies | Access to request cookies |
Skew Protection Settings
| Setting | Type | Effect |
|---|---|---|
skewProtection | Boolean | Enables version sync |
Best Practices
✅ Do This:
// Use matcher to avoid running on static files
export const config = { matcher: ['/((?!api|_next|.*\\..*).*)'] }; // ✅
// Keep middleware logic minimal and fast
return NextResponse.next(); // ✅
// Always clone headers when modifying
const requestHeaders = new Headers(request.headers); // ✅
// Handle redirects with absolute URLs
return NextResponse.redirect(new URL('/path', request.url)); // ✅
❌ Don’t Do This:
// Run middleware on all requests including assets
// No matcher defined // ❌
// Use complex DB calls (Middleware must be fast)
await db.users.findMany(); // ❌
// Forget to handle the base path in redirects
return NextResponse.redirect('/login'); // ❌
// Use node-specific APIs
import fs from 'fs'; // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Infinite Loop | Redirecting to a path middleware matches | Add matcher exclusion |
| Static files lag | Middleware running on _next chunks | Exclude _next in matcher |
| Size limits | Middleware bundle too large | Keep dependencies light |
| Async blocking | Awaiting heavy logic | Use cached/simple checks |
Real-World Examples
1. Simple redirect
return NextResponse.redirect(new URL('/home', request.url));
2. Locale-based rewrite
return NextResponse.rewrite(new URL(`/${locale}${pathname}`, request.url));
3. Setting a header
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-user-id', userId);
return NextResponse.next({ request: { headers: requestHeaders } });
4. JSON API response
return NextResponse.json({ success: false }, { status: 401 });
5. Cookie check
const token = request.cookies.get('token');
if (!token) return NextResponse.redirect('/login');
6. Geo-blocking
if (request.geo?.country === 'XY') return NextResponse.rewrite('/blocked');
7. Skew protection config
{ "skewProtection": true }
8. Path stripping
url.pathname = url.pathname.replace('/api/', '/');
return NextResponse.rewrite(url);
9. Absolute URL construction
new URL('/login', request.url)
10. Ignoring internal paths
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)']
Visual
The Middleware Lifecycle
┌────────────────────────────────────────────────────────┐
│ USER REQUEST │
│ │ │
│ ▼ │
│ VERCEL EDGE NETWORK │
│ ┌──────────────────────┐ │
│ │ MIDDLEWARE.TS │ <── Logic (Auth, Rewrite) │
│ └──────────────────────┘ │
│ │ │
│ ▼ │
│ ORIGIN / SERVERLESS FUNCTION / STATIC ASSET │
└────────────────────────────────────────────────────────┘
Skew Protection Flow
┌────────────────────────────────────────────────────────┐
│ BROWSER SERVER │
│ Load old JS ──► (New Deploy) ──► Mismatch! │
│ Fetch chunk ──► 404 (Missing) ──► Trigger Reload │
│ │
│ User gets new version automatically │
└────────────────────────────────────────────────────────┘
Request Filtering
┌────────────────────────────────────────────────────────┐
│ PATH MATCH? ACTION │
│ /dashboard YES Run Middleware │
│ /login YES Run Middleware │
│ /static/img NO Skip (Fast) │
│ /_next/js NO Skip (Fast) │
└────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Location | Edge Network |
| Logic file | middleware.ts |
| Request type | NextRequest |
| Response type | NextResponse |
| Scope control | matcher |
| Sync feature | skewProtection |
| Restriction | No Node.js native APIs |
Key takeaways:
- Middleware intercepts requests at the Edge. By executing logic before the request hits the origin, you can perform authentication, redirects, and rewrites with near-zero latency.
- Always use a matcher. Without a
config.matcher, middleware executes for every single request, including images and static assets, which creates significant performance overhead. - Middleware is a Web API environment. You must use standard Web
Request/ResponseAPIs; Node.js specific libraries likefsorpathare unavailable and will cause runtime errors. - Skew Protection is essential. Enabling
skewProtectioninvercel.jsonsolves the common issue of users navigating with stale client-side assets after a new deployment is pushed to production. - Use rewrites for localization. Rewrites allow you to serve content from different paths based on headers or cookies without the browser URL ever changing.
Remember: Middleware is your first line of defense and routing control, but it is not a backend server. Keep your logic lightweight, fast, and dependency-free to ensure it adds speed rather than latency. When combined with Skew Protection, you create a robust deployment strategy that protects users from version mismatches and serves them the correct content based on their context.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!