Loading lessons...
Route Protection & Redirects
Route Protection & Redirects
Protecting sensitive application routes (such as dashboards, settings, or admin panels) is one of the primary use cases for Next.js Middleware.
Implementing Route Protection in Middleware
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// Routes requiring authentication
const protectedRoutes = ['/dashboard', '/account', '/settings'];
const authRoutes = ['/login', '/register'];
export function middleware(request: NextRequest) {
const token = request.cookies.get('session_token')?.value;
const { pathname } = request.nextUrl;
const isProtectedRoute = protectedRoutes.some((route) =>
pathname.startsWith(route)
);
const isAuthRoute = authRoutes.some((route) => pathname.startsWith(route));
// 1. Redirect unauthenticated user attempting to access protected route
if (isProtectedRoute && !token) {
const loginUrl = new URL('/login', request.url);
loginUrl.searchParams.set('callbackUrl', pathname); // Store intent
return NextResponse.redirect(loginUrl);
}
// 2. Redirect authenticated user away from login/register pages to dashboard
if (isAuthRoute && token) {
return NextResponse.redirect(new URL('/dashboard', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*', '/account/:path*', '/settings/:path*', '/login', '/register'],
};
Redirect vs Rewrite
| Action | API | Browser URL Bar | Use Case |
|---|---|---|---|
| Redirect | NextResponse.redirect(url) | Changes to target URL | Auth login redirects, legacy URL moves |
| Rewrite | NextResponse.rewrite(url) | Remains unchanged | A/B testing, internal API proxying |
Security Best Practices for Middleware Auth
⚠️ DocHero Safety Disclaimer
Middleware runs on the Edge Edge runtime and cannot perform heavy Node.js cryptographic checks or full database queries easily. Always perform lightweight session token verification (such as checking cookie presence or verifying a fast JWT signature) in Middleware, while enforcing detailed authorization checks inside your Server Components and Server Actions!
TL;DR
- Read session cookies in middleware using
request.cookies.get('token'). - Redirect unauthorized users using
NextResponse.redirect(loginUrl). - Pass
callbackUrlquery parameters to return users to their destination after login. - Use
NextResponse.rewrite()for transparent proxying without URL changes.