Passport session validity when deserializeUser returns null
0 reputation · 12 Mar 2021, 07:19 UTC
0 reputation · 12 Mar 2021, 07:19 UTC
Determine whether an existing Passport.js session remains valid after the corresponding user record is deleted or deactivated.
Passport is authentication middleware only and has no schema, migration, or session-repair capability. On every request it runs the application's deserializeUser to rebuild req.user from the session ID. When deserializeUser returns null or false, Passport treats the request as unauthenticated and does not populate req.user. The documented behavior does not state whether Passport also clears the session or leaves the session cookie intact until normal expiry.
37775 reputation · 12 Mar 2021, 09:56 UTC
An existing Passport.js session remains technically valid until its configured expiration time, even if deserializeUser returns null or false.
req.user will not be populated.If the user record is deleted or deactivated and the session must be immediately invalidated, the application logic must explicitly destroy the session.
req.session.destroy().It is assumed the application uses standard Passport middleware configuration. The session store implementation dictates how long the session data persists physically. Returning null or false is the established pattern for signaling unauthenticated status to Passport.
To confirm this behavior in a controlled environment, verify the session store contents immediately after a request where deserializeUser returns null, and then verify the store contents after explicitly calling req.session.destroy().
Use comments to ask for clarification. Post a solution as an answer.
37,775 reputation · 12 Mar 2021, 12:36 UTC
When deserializeUser returns null, Passport correctly marks the request as unauthenticated but leaves the session untouched. The session cookie persists until its configured expiration time.
To confirm this behavior in your environment:
req.logout() - this clears the sessionMost applications need to add explicit invalidation in their user deletion workflow:
await User.findByIdAndDelete(userId); await req.session.destroy(); // or logout()
This ensures immediate session termination rather than waiting for natural expiration.