Performance: JWT vs session strategy
This affects page load speed and interaction responsiveness by influencing server requests, token size, and client-side processing.
Jump into concepts and practice - no test required
Using JWT stored in HTTP-only cookies with minimal server validation.Using server sessions with frequent server lookups on every request without caching.
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Server session with frequent lookups | Low | Multiple per request | Medium | [X] Bad |
| JWT with large payload | Low | Few | High due to parsing | [!] OK |
| JWT with minimal payload | Low | Few | Low | [OK] Good |
| Server-side session validation with SSR | Low | Single | Low | [OK] Good |
import jwt from 'jsonwebtoken';
export default function handler(req, res) {
try {
const token = req.headers.authorization?.split(' ')[1];
jwt.verify(token, process.env.JWT_SECRET);
res.status(200).json({ message: 'Access granted' });
} catch (err) {
res.status(401).json({ error: 'Invalid or expired token' });
}
}import { getSession } from 'next-auth/react';
export default async function handler(req, res) {
const session = getSession();
if (!session) {
res.status(401).json({ error: 'Not authenticated' });
} else {
res.status(200).json({ message: 'Welcome!' });
}
}