🚀 Express.js Intermediate

What is express-session and how does session-based auth work?

Answer

express-session is middleware that stores session data server-side and sends a session ID cookie to the client. Install and configure: app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, store: new RedisStore({ client }) }));. After login: req.session.userId = user.id;. On subsequent requests, the cookie is sent back, the session is loaded, and req.session.userId is populated. req.session.destroy() logs out the user. For production, store sessions in Redis or a database instead of in-memory (default) — in-memory sessions are lost on restart and not shared between multiple server instances. Session-based auth is stateful; JWT is stateless.