Securing Next.js App Router with Middleware
Route protection in Next.js has evolved significantly with the introduction of edge middleware.
Why Middleware?
Before middleware, route protection happened on the client side (causing flash of unauthenticated content) or inside each getServerSideProps function individually. Middleware allows us to intercept incoming HTTP requests at the edge before any route handler runs.
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const token = request.cookies.get('token')?.value;
if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
Key Practices
- Store auth tokens in
HttpOnly,SameSite=Laxcookies. - Match routes carefully using the
matcherconfiguration. - Handle token expiration gracefully with redirects.