Sessions vs. JWT: Where to Keep the Keys

Sessions vs. JWT: Where to Keep the Keys in JavaScript: HTTP forgets you between every request.

Concept Explanation

HTTP forgets you between every request. Login is therefore not one problem but two: proving who you are once, and proving it again on the next 400 requests without asking for the password each time.

There are two classic answers.

Sessions are a coat check. The server keeps your coat (the user record) and hands you a numbered ticket. The ticket is meaningless to anyone else, and the cloakroom can refuse it at any moment.

JWTs are a festival wristband. All the information is printed on the band itself and signed so it cannot be forged. Nobody needs to look you up. But once it is on your wrist, it is valid until it expires, and the gate cannot easily take it back.

That last sentence is the whole trade-off: sessions are revocable but need lookups; JWTs are stateless but stubborn.


Syntax or Core Structure

Session cookie

app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  store: new RedisStore({ client: redis }),
  cookie: {
    httpOnly: true,     // JS cannot read it
    secure: true,       // HTTPS only
    sameSite: 'lax',    // blunts CSRF
    maxAge: 1000 * 60 * 60 * 24
  }
}));

JWT with a refresh pair

const access  = jwt.sign({ sub: user.id, role: user.role },
                         process.env.JWT_SECRET, { expiresIn: '15m' });
const refresh = jwt.sign({ sub: user.id },
                         process.env.REFRESH_SECRET, { expiresIn: '30d' });

// Verify on each request
const payload = jwt.verify(token, process.env.JWT_SECRET);

Key Features

SessionJWT
Server stores stateYes (DB or Redis)No
Instant logout / banYesNot without a blocklist
Scales across servicesNeeds a shared storeNaturally
Payload visible to userNoYes, it is only base64
Typical carrierCookieAuthorization header

A JWT is three base64 segments joined by dots: header, payload, signature. The signature proves nobody edited it. It does not encrypt anything, so never put a secret in the payload.


Real World Example

A monolith versus a fleet. A single Express app with one database is simplest with sessions: you already have Redis, logout is a one-line delete, and httpOnly cookies keep tokens out of reach of XSS.

A mobile app hitting six microservices is simplest with JWTs: each service verifies the signature locally with a public key, and no service needs to call an auth server on every request. The price is that revocation becomes a design problem you must solve on purpose, usually with short access tokens plus a refresh token you can revoke.

Many teams end up with the hybrid: short-lived JWT for the API, long-lived refresh token stored in an httpOnly cookie.


Common Mistakes

  • Keeping tokens in localStorage. Any XSS bug becomes total account takeover, because injected JavaScript can simply read it. httpOnly cookies cannot be read by script at all.
  • Long-lived access tokens. A 30-day JWT is a 30-day skeleton key you cannot recall. Minutes, not weeks.
  • Trusting the payload without verifying. Decoding is not validating. Always verify, and pin the expected algorithm.
  • Accepting alg: none. A classic bypass: the attacker strips the signature and some libraries used to shrug. Pin the algorithm explicitly.
  • Hand-rolling password hashing. Use bcrypt or argon2. Never a bare SHA-256, never your own scheme.
  • Assuming JWT means CSRF-proof. True only while the token lives in a header. Put it in a cookie and CSRF is back.

Best Practices

  • Default to sessions for a server-rendered app; reach for JWTs when statelessness is a real requirement, not an aesthetic one.
  • Access tokens measured in minutes, refresh tokens rotated on every use, and revoked on reuse.
  • Read secrets from environment variables, never from source. Rotate them on a schedule.
  • Rate-limit login and reset endpoints, and use a constant-time comparison for anything secret.
  • Regenerate the session ID on login to prevent session fixation.

Practice Exercises

  1. The Token Autopsy: Paste a sample JWT into a decoder, read the three parts, and confirm you can see the payload without any secret. Write down what that means for what you may store there.
  2. The Logout Problem: Implement logout for both schemes. For sessions, delete the store entry. For JWTs, design a blocklist and note what it costs you in statelessness.
  3. The Storage Comparison: Store a token in localStorage, then read it from the console. Repeat with an httpOnly cookie and explain why the second attempt fails.