javascript / intermediate
Snippet
Route Protection with Middleware
Middleware runs before a request is completed, allowing you to intercept and redirect users based on authentication status.
snippet.js
1
2
3
4
5
6
export function middleware(request) {const token = request.cookies.get('session');if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {return NextResponse.redirect(new URL('/login', request.url));}}
nextjs
Breakdown
1
const token = request.cookies.get('session')
Retrieves the session cookie from the incoming request object.
2
return NextResponse.redirect(...)
Redirects the user to the login page if the required session token is missing.