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
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, filter, take, switchMap } from 'rxjs/operators';
Refreshing auth tokens in an Angular interceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 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.