javascript
48 lines · 8 steps
JWT session cookies in a Next.js Route Handler
A POST signs a JWT into an httpOnly cookie and a GET verifies it to return the current user.
Explained by
highlit
1import { cookies } from 'next/headers';
2import { NextResponse } from 'next/server';
3import { SignJWT, jwtVerify } from 'jose';
4
5const secret = new TextEncoder().encode(process.env.AUTH_SECRET);
6
7export async function POST(request) {
8 const { email, password } = await request.json();
9
10 const user = await authenticate(email, password);
11 if (!user) {
12 return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
13 }
14
15 const token = await new SignJWT({ sub: user.id, role: user.role })
16 .setProtectedHeader({ alg: 'HS256' })
17 .setIssuedAt()
18 .setExpirationTime('7d')
19 .sign(secret);
20
21 const cookieStore = await cookies();
22 cookieStore.set('session', token, {
23 httpOnly: true,
24 secure: process.env.NODE_ENV === 'production',
25 sameSite: 'lax',
26 path: '/',
27 maxAge: 60 * 60 * 24 * 7,
28 });
29
30 return NextResponse.json({ id: user.id, email: user.email });
31}
32
33export async function GET() {
34 const cookieStore = await cookies();
35 const token = cookieStore.get('session')?.value;
36
37 if (!token) {
38 return NextResponse.json({ user: null }, { status: 401 });
39 }
40
41 try {
42 const { payload } = await jwtVerify(token, secret);
43 return NextResponse.json({ user: { id: payload.sub, role: payload.role } });
44 } catch {
45 cookieStore.delete('session');
46 return NextResponse.json({ user: null }, { status: 401 });
47 }
48}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Storing a signed JWT in an httpOnly cookie keeps the session token out of reach of client-side JavaScript.
- 2Encoding the secret once and reusing it for both signing and verifying keeps the symmetric HS256 flow consistent.
- 3Verification failures should clear the bad cookie so a corrupt or expired token doesn't linger on the client.
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
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 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/jwt-session-cookies-in-a-next-js-route-handler-explained-javascript-6c35/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.