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
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
php
<?php namespace App\Http\Middleware;
Resolving the current team in Laravel middleware
middleware
multi-tenancy
cookies
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback } from 'react'; function getColumnCount(width) { if (width < 640) return 1;
A responsive column hook in React
custom-hooks
debouncing
responsive-design
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/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.