After login, the server needs to remember the user. There are two main ways.
Server sessions JWT Stored Server (Redis/DB); the cookie holds only an ID The token itself holds the claims Logout / revoke Easy: delete the session Hard: the token is valid until it expires Scaling Needs a shared store Stateless Best for Web apps Service-to-service, mobile, short-lived access tokens
Packages
Package Use 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
Access token: short (5–15 min)
Refresh token: long (days), in an HttpOnly cookie, stored hashed in the DB
Each refresh hands out a new refresh token and invalidates the old one
If an old refresh token is reused, it was stolen: revoke the whole token family
Checklist