advanced

Sessions and cookies

Use server-side sessions or signed cookies with Secure, HttpOnly, SameSite, expiry, rotation, revocation, and CSRF-aware request design.

Session-based auth stores server-side state keyed by a session ID delivered in an HttpOnly cookie. The browser sends the cookie automatically on same-site requests; the server looks up session data in Redis, a database, or signed encrypted cookies (stateless sessions).

					// After login — set session cookie
res.cookie('sid', sessionId, {
  httpOnly: true,
  secure: true,
  sameSite: 'lax',
  maxAge: 3600_000,
  path: '/',
});

// Middleware — load session before routes
async function loadSession(req, res, next) {
  const sid = req.cookies.sid;
  req.session = sid ? await store.get(sid) : null;
  next();
}
				

Rotate session IDs on privilege elevation (login). Support revocation by deleting server-side records. Pair cookie sessions with CSRF protection for state-changing requests when SameSite is not Strict.

On interviews: contrast server-side sessions vs JWT in cookies; explain fixation attacks and rotation; why HttpOnly blocks XSS token theft but not CSRF.

Common pitfalls: storing large objects in cookies; session IDs in URLs; no TTL or idle timeout; shared session store single point of failure without HA.

The trade-off is balancing simplicity, performance, safety, and operability — name which axis you optimized and what cost you accepted.

Checklist:

  • HttpOnly, Secure, deliberate SameSite.
  • Server-side lookup with expiry and rotation.
  • CSRF tokens or Strict SameSite for mutations.
  • External session store for horizontal scale.