Sequence NODE_217
MediumUse Middleware for Simple Auth Redirect
Next.js
JavaScript
Technical Specification
Use middleware.ts to protect a dashboard route and redirect to login if no cookie is set.
Input/Output Samples
Input:visit /dashboard without auth cookie
Output:redirect to /login
Optimal Logic Path
import { NextResponse } from "next/server";
export function middleware(request) {
const hasAuth = request.cookies.get("auth_token");
if (!hasAuth && request.nextUrl.pathname.startsWith("/dashboard")) {
const url = new URL("/login", request.url);
return NextResponse.redirect(url);
}
return NextResponse.next();
}Architectural Deep-Dive
Middleware runs before the route and can redirect based on cookies or headers.