Express Session Setup for Passport.js Authentication

Why express-session is required in Passport.js

express-session is the core middleware that enables session management in an Express application. In Passport.js, it plays a critical role because session-based authentication depends on storing user data on the server side. Without express-session, Passport cannot persist login states, which means serializeUser and deserializeUser will not function as expected.

How express-session works with Passport

When a user logs in successfully, Passport uses serializeUser to store a minimal identifier, usually the user ID, inside the session. This session is created and managed by express-session. On every subsequent request, express-session retrieves this stored data and makes it available to Passport, which then calls deserializeUser to rebuild the full user object and attach it to req.user.

Proper setup flow for authentication

In a typical Express application, express-session must be configured before passport.session() middleware. This order is important because Passport relies on session data being available before it can deserialize users. Once configured correctly, this setup allows users to stay logged in across multiple requests while keeping authentication secure and efficient.