0 day streak
javascript / intermediate
Snippet

Edge-Based Route Protection in Middleware

Middleware runs before a request is completed. It is the ideal place to implement authentication checks globally, ensuring that protected routes are never even rendered for unauthorized users.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const token = request.cookies.get('auth-token');
if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
nextjs
Breakdown
1
request.cookies.get('auth-token')
Efficiently accesses cookies directly at the edge without hitting the origin server.
2
request.nextUrl.pathname.startsWith('/dashboard')
Checks if the user is trying to access a protected route segment.
3
NextResponse.redirect(...)
Immediately redirects the user to the login page if the authentication check fails.