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.
Previous
How do you implement pagination in an Express REST API?
Next
How do you implement file uploads in Express.js?
More Express.js Questions
View all →- Intermediate How do you implement JWT authentication in Express.js?
- Intermediate What is Express middleware chaining and how does it work?
- Intermediate What is the helmet package and why should you use it?
- Intermediate How do you implement rate limiting in Express.js?
- Intermediate What is input validation and how do you do it in Express?