javascript 50 lines · 8 steps

Gating routes with Next.js middleware and JWTs

A Next.js middleware verifies session cookies at the edge and redirects unauthenticated users away from protected routes.

Explained by highlit
1import { NextResponse } from 'next/server';
2import { jwtVerify } from 'jose';
3 
4const PROTECTED_PREFIXES = ['/dashboard', '/settings', '/billing'];
5 
6const encoder = new TextEncoder();
7const secret = encoder.encode(process.env.SESSION_SECRET);
8 
9async function verifySession(token) {
10 try {
11 const { payload } = await jwtVerify(token, secret, {
12 algorithms: ['HS256'],
13 });
14 return payload;
15 } catch {
16 return null;
17 }
18}
19 
20export async function middleware(request) {
21 const { pathname } = request.nextUrl;
22 
23 const isProtected = PROTECTED_PREFIXES.some(
24 (prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`)
25 );
26 
27 if (!isProtected) {
28 return NextResponse.next();
29 }
30 
31 const token = request.cookies.get('session')?.value;
32 const session = token ? await verifySession(token) : null;
33 
34 if (!session) {
35 const loginUrl = new URL('/login', request.url);
36 loginUrl.searchParams.set('from', pathname);
37 
38 const response = NextResponse.redirect(loginUrl);
39 response.cookies.delete('session');
40 return response;
41 }
42 
43 const response = NextResponse.next();
44 response.headers.set('x-user-id', String(session.sub));
45 return response;
46}
47 
48export const config = {
49 matcher: ['/dashboard/:path*', '/settings/:path*', '/billing/:path*'],
50};
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Running auth checks in middleware guards protected routes before any page code executes.
  2. 2The edge-compatible jose library verifies JWTs without Node crypto, and failed verification should fail closed to null.
  3. 3Middleware can enrich requests by forwarding trusted claims as headers to downstream handlers.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Gating routes with Next.js middleware and JWTs — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code