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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Running auth checks in middleware guards protected routes before any page code executes.
- 2The edge-compatible jose library verifies JWTs without Node crypto, and failed verification should fail closed to null.
- 3Middleware can enrich requests by forwarding trusted claims as headers to downstream handlers.
Related explainers
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/gating-routes-with-next-js-middleware-and-jwts-explained-javascript-5238/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.