Understanding req.user in Passport.js Authentication
What req.user represents in Passport.js
In Passport.js, req.user is the object that represents the currently authenticated user in a request. It is automatically added by Passport after the authentication process is completed and the session is validated. This allows developers to access user information in any route without manually querying the database every time.
How deserializeUser sets req.user
The req.user object is populated during the deserializeUser phase. When a request comes in, Passport retrieves the user identifier stored in the session and passes it to deserializeUser. Inside this function, the application fetches the full user record from the database and returns it. Passport then attaches this returned object to req.user, making it available throughout the request lifecycle.
Why req.user is important in protected routes
req.user is essential for building protected routes because it acts as proof that the user is authenticated. Instead of rechecking credentials, the application simply checks whether req.user exists. If it does, the user is considered logged in and allowed access to restricted resources. This makes route protection simple, efficient, and consistent across the application.