🟢 Node.js Intermediate

What is session management in Node.js?

Why Interviewers Ask This

Mid-level Node.js roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

Session management maintains state across multiple HTTP requests for a user (HTTP is stateless by default). Server-side sessions store session data (user ID, cart, preferences) on the server, sending only a session ID cookie to the client. In Express.js, use express-session: app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, cookie: { secure: true, httpOnly: true, maxAge: 24 * 60 * 60 * 1000 } }));. By default, sessions are stored in memory (MemoryStore) — only suitable for development. In production, use persistent stores: Redis (connect-redis) for fast, shared session storage across multiple server instances; PostgreSQL or MongoDB (connect-mongo). Cookie security flags: httpOnly (prevents JS access, XSS protection), secure (HTTPS only), sameSite (CSRF protection). Sessions vs JWT: sessions are stateful (revocable, storage required); JWTs are stateless (no server storage, hard to revoke before expiry).

Common Mistake

Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real Node.js project.