Loading Depth Study
Preparing your workspace
Next.js middleware can inspect requests before they reach selected routes and apply shared request-level logic.
Middleware can be useful for routing decisions that should happen before a page or route handler executes. Examples include redirects, locale handling, selected authentication checks, or adding request-level behavior. Middleware should remain focused because not every operation belongs there. Heavy database logic or complex business rules are usually better placed in appropriate server-side services. Route and data authorization must still be enforced at the actual security boundary.
A Next.js application can use middleware to redirect unauthenticated users away from dashboard routes.
import { NextResponse } from 'next/server';
export function middleware(request) {
const hasSession = Boolean(request.cookies.get('session'));
if (!hasSession && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}Unauthenticated requests to dashboard paths are redirected to the login page.