Middleware
Request interception, authentication, redirects, headers, and edge runtime.
Overview
Middleware runs before a request is completed, enabling authentication and request modification.
Key Concepts
- Edge Runtime — Runs at the edge for low latency
- Request/Response — Modify headers, cookies, redirect
- Authentication — Check tokens before route access
- A/B Testing — Route users to different variants
- Geolocation — Access user location data
Code Examples
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(request) {
const token = request.cookies.get('token');
const isAuthenticated = !!token;
// Protect dashboard routes
if (request.nextUrl.pathname.startsWith('/dashboard') && !isAuthenticated) {
return NextResponse.redirect(new URL('/login', request.url));
}
// Add custom headers
const response = NextResponse.next();
response.headers.set('x-user-id', token?.value || 'anonymous');
return response;
}
// Advanced middleware with geolocation
export function middleware(request) {
const country = request.geo?.country;
// Redirect based on location
if (request.nextUrl.pathname === '/') {
if (country === 'US') {
return NextResponse.redirect(new URL('/en', request.url));
}
return NextResponse.redirect(new URL('/es', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*', '/api/:path*']
};
Practice
Implement authentication middleware with role-based access control.