10. Middleware & Routing
10.1 What is Middleware?
Middleware runs before every request is processed — at the edge, before the cache is checked. It's the right place for:
// middleware.ts (runs on Edge Runtime)
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const token = request.cookies.get('auth-token');
// Authentication redirect
if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
// A/B testing
const variant = Math.random() < 0.5 ? 'a' : 'b';
const response = NextResponse.next();
response.cookies.set('ab-variant', variant);
return response;
// Geolocation personalisation
const country = request.geo?.country;
if (country === 'DE') {
return NextResponse.redirect(new URL('/de' + request.nextUrl.pathname, request.url));
}
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
10.2 What Middleware should NOT do
- Database queries (no persistent connections in Edge Runtime)
- Complex business logic (35ms CPU limit)
- Large npm packages (size limit: 1MB)
- Caching responses
10.3 Vercel's Routing Middleware (formerly Edge Middleware)
Since mid-2025, Vercel unified "Edge Middleware" and "Edge Functions" under "Vercel Functions using the Edge Runtime." Middleware is now the term for request interception before routing.