Next.js Middleware explains how to intercept incoming HTTP requests before they complete, enabling edge-level redirects, rewrites, and header modifications.
Middleware runs on the Edge runtime before route handlers or page layouts execute. Place a single middleware.ts file in the root of your project to intercept requests.
flowchart TD
A["Incoming HTTP Request"] --> B["middleware.ts Execution"]
B --> C{"Check Auth Cookie?"}
C -- "Missing Token" --> D["NextResponse.redirect('/login')"]
C -- "Valid Token" --> E["NextResponse.next()"]
E --> F["Route Handler / Page Component"]
Export a default middleware function to inspect incoming cookies or headers:
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const token = request.cookies.get('session-token');
const isAuthPage = request.nextUrl.pathname.startsWith('/login');
const isDashboardPage = request.nextUrl.pathname.startsWith('/dashboard');
// Redirect unauthenticated users away from protected routes
if (isDashboardPage && !token) {
return NextResponse.redirect(new URL('/login', request.url));
}
// Redirect authenticated users away from login page
if (isAuthPage && token) {
return NextResponse.redirect(new URL('/dashboard', request.url));
}
return NextResponse.next();
}
// Filter which paths middleware executes on
export const config = {
matcher: ['/dashboard/:path*', '/login'],
};
/en or /es.You can inject custom security headers or request context data into downstream components:
// middleware.ts - Setting Custom Headers
const response = NextResponse.next();
response.headers.set('x-custom-header', 'my-custom-value');
return response;
matcher Option: Limit middleware execution to required routes to avoid slowing down static asset requests.Next.js Middleware offers high-speed request interception at the network edge. It simplifies route protection, redirects, and header manipulation across your application.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With