Sessions and JWT

After login, the server needs to remember the user. There are two main ways.

Server sessionsJWT
StoredServer (Redis/DB); the cookie holds only an IDThe token itself holds the claims
Logout / revokeEasy: delete the sessionHard: the token is valid until it expires
ScalingNeeds a shared storeStateless
Best forWeb appsService-to-service, mobile, short-lived access tokens

Packages

PackageUse
express-session + connect-redisServer-side sessions
jsonwebtokenSign and verify JWTs
joseModern JWT/JWE/JWKS library (works everywhere)
cookie-parserRead cookies

✅ Sessions

app.use(session({
  store: new RedisStore({ client: redis }),
  secret: process.env.SESSION_SECRET,
  name: 'sid',                 // don't reveal "connect.sid" / the framework
  resave: false,
  saveUninitialized: false,
  cookie: { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 1000 * 60 * 60 },
}));

// After login: new session ID (stops session fixation)
req.session.regenerate(() => { req.session.userId = user.id; res.end(); });

❌ JWT mistakes

jwt.decode(token);                        // ❌ decode does NOT verify the signature
jwt.verify(token, secret);                // ⚠️ pin the algorithm, or "alg: none"/confusion attacks may work
jwt.sign({ user, password }, 'secret');   // ❌ the payload is only base64, anyone can read it; weak secret
localStorage.setItem('token', token);     // ⚠️ any XSS can steal it

✅ JWT done right

const access = jwt.sign({ sub: user.id, role: user.role }, process.env.JWT_SECRET, {
  algorithm: 'HS256', expiresIn: '15m', issuer: 'myapp', audience: 'myapp-api',
});

const payload = jwt.verify(token, process.env.JWT_SECRET, {
  algorithms: ['HS256'], issuer: 'myapp', audience: 'myapp-api',
});

Refresh token rotation

  1. Access token: short (5–15 min)
  2. Refresh token: long (days), in an HttpOnly cookie, stored hashed in the DB
  3. Each refresh hands out a new refresh token and invalidates the old one
  4. If an old refresh token is reused, it was stolen: revoke the whole token family

Checklist

  • Cookies: HttpOnly, Secure, SameSite
  • Regenerate the session ID on login and on privilege change
  • Destroy the session on logout and on password change
  • JWT: pin algorithms, short expiresIn, check iss/aud
  • JWT secret ≥ 256 bits of randomness, or use RS256/EdDSA key pairs
  • No sensitive data in the JWT payload