javascript / expert
Snippet
Secure Middleware Pattern for Edge-Level Authentication
Using Middleware for authentication allows you to intercept requests before they even reach your page logic. Running this on the Edge provides a fast, centralized security layer that prevents unauthorized access to protected routes.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { NextResponse } from 'next/server';import type { NextRequest } from 'next/request';import { verifyToken } from '@/lib/auth';export async function middleware(request: NextRequest) {const token = request.cookies.get('session')?.value;const verified = token && (await verifyToken(token));if (!verified && request.nextUrl.pathname.startsWith('/admin')) {return NextResponse.redirect(new URL('/login', request.url));}return NextResponse.next();}
nextjs
Breakdown
1
const token = request.cookies.get('session')?.value;
Retrieves the session token directly from the request headers at the Edge.
2
return NextResponse.redirect(...);
Immediately reroutes unauthenticated users, saving server resources.