javascript / intermediate
Snippet
Route Protection with Middleware
Next.js Middleware runs before every request. It is the ideal place to implement authentication checks globally, ensuring that protected pages are never reached by unauthenticated users.
snippet.js
1
2
3
4
5
6
7
8
9
10
import { NextResponse } from 'next/server';export function middleware(request) {const token = request.cookies.get('auth-token');const { pathname } = request.nextUrl;if (!token && pathname.startsWith('/dashboard')) {return NextResponse.redirect(new URL('/login', request.url));}}
nextjs
Breakdown
1
request.cookies.get('auth-token')
Checks for the presence of an authentication cookie.
2
pathname.startsWith('/dashboard')
Identifies if the user is trying to access a protected route.
3
NextResponse.redirect(...)
Sends the user back to login if the auth check fails.