passport
semver
>=0.7.0 <1.0.0postconditions23functions10last verified2026-04-16coverage score91%Postconditions — what we check
- authenticate · authenticate-failureerrorWhenauthentication fails (invalid credentials, missing user, strategy error)Returnsmiddleware that may call callback with error or fail objectRequired handlingCaller MUST handle authentication failures in callback or error middleware. Use custom callback (req, res, next) => passport.authenticate('strategy', (err, user, info) => {...}) to handle errors, missing users, and validation failures.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[1]
- authenticate · authenticate-strategy-errorerrorWhenstrategy encounters error (database down, network timeout, invalid configuration)Returnsmiddleware that calls callback with error as first argumentRequired handlingCaller MUST handle strategy errors in callback or Express error handler. Check if (err) in custom callback and forward to next(err) for centralized error handling.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[1]
- authenticate · authenticate-unknown-strategyerrorWhenpassport.authenticate() is called with a strategy name that has not been registered via passport.use(). The strategy lookup returns undefined.Throws
Error('Unknown authentication strategy "<name>"') — forwarded via next(err) to the Express error handler. Confirmed from lib/middleware/authenticate.js: 'if (!prototype) { return next(new Error("Unknown authentication strategy \"" + layer + "\"")); }'Required handlingAlways register strategies with passport.use() before calling passport.authenticate(). Typos in strategy names, missing passport-strategy packages, or conditional registration (only registering strategies in some environments) all cause this error at request time, not at startup. Use a centralized Express error handler to catch this gracefully.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[2] - logIn · login-missing-session-middlewareerrorWhenreq.logIn() is called but no session middleware (express-session) has been configured, so req.session is undefined.Throws
Error('Login sessions require session support. Did you forget to use `express-session` middleware?') passed to done callbackRequired handlingCaller MUST pass a done callback and check the err argument. If err is present, forward to next(err). Also ensure express-session (or equivalent) is mounted before passport.initialize().costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible - logIn · login-session-save-errorerrorWhenSession persistence fails during req.logIn() — typically because the session store (Redis, Postgres, etc.) is unavailable when session.save() is called. Also occurs if the session.regenerate() call fails.Throws
Error from session store propagated to done callback — commonly a connection error from the underlying session store (e.g., ioredis disconnection, Postgres connection timeout).Required handlingCaller MUST provide a done callback. If err is truthy, the user is NOT logged in (req.user is set to null). Caller MUST call next(err) or respond with 500 — silently ignoring this error leaves the user appearing logged in on the client but not in the server session.costhighin prodsilent failureusers seeauthentication failurevisibilitysilent - logIn · login-serialize-errorerrorWhenThe registered serializeUser function calls done(err) with an error, or throws synchronously. This causes login session establishment to fail.Throws
Error propagated from serializeUser's done(err) call to the logIn callbackRequired handlingCaller MUST check err in the logIn callback. Common causes: database unavailability when looking up user ID, or serializer logic bug. Always forward to next(err) for centralized error handling.costmediumin prodsilent failureusers seeauthentication failurevisibilitysilentSources[5] - logIn · login-missing-callbackerrorWhenreq.logIn() is called with session:true (default) but no callback function is provided.Throws
Error('req#login requires a callback function') — thrown synchronouslyRequired handlingAlways provide a callback to req.logIn() when session:true (the default). Use { session: false } only for stateless API authentication.costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[6] - logout · logout-missing-callbackerrorWhenreq.logout() is called but no callback function is provided. In passport >= 0.6.0, a callback is required because session.save() is async.Throws
Error('req#logout requires a callback function') — thrown synchronouslyRequired handlingAlways provide a callback: req.logout(function(err) { if (err) { return next(err); } ... }). Calling req.logout() without a callback was valid in passport < 0.6 but now throws synchronously, crashing the request.costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible - logout · logout-session-save-errorerrorWhenSession persistence fails during req.logout() — session.save() errors when the session store (Redis, Postgres, memcached) is unavailable, or session.regenerate() fails during the secure logout flow.Throws
Error from session store propagated to done callbackRequired handlingCaller MUST check err in the callback and forward to next(err). If silently ignored, the session may not be destroyed in the store — the user appears logged out on the client but their session remains valid server-side, creating a security vulnerability.costhighin prodsilent failureusers seesecurity breachvisibilitysilent - logout · logout-missing-session-middlewareerrorWhenreq.logout() is called but no session middleware is mounted — req.session is undefined.Throws
Error('Login sessions require session support. Did you forget to use `express-session` middleware?') passed to callbackRequired handlingEnsure express-session (or equivalent) is mounted before passport middleware. Always check err in the callback.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[4] - session · session-missing-session-middlewareerrorWhenpassport.session() runs but express-session middleware has not been mounted, so req.session is undefined.Throws
Error('Login sessions require session support. Did you forget to use `express-session` middleware?') — propagated via next(err) to Express error handlerRequired handlingMount express-session (or compatible session middleware) before passport.initialize() and passport.session() in the middleware stack. If session middleware is missing, all requests hit the error handler.costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[8] - session · session-deserialize-errorerrorWhenThe registered deserializeUser function calls done(err) with an error — typically a database query failure when looking up the user by ID from the session. This triggers on every authenticated request, not just at login time.Throws
Error propagated via next(err) to the Express error handler on every request where a login session existsRequired handlingThe deserializeUser callback MUST distinguish between "user not found" (call done(null, false)) and "database error" (call done(err)). A database error causes every session-backed request to fail with 500. Implement retry or fallback behavior in the deserializer. Also mount an Express error handler to prevent unhandled crash.costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible - session · session-failed-deserialize-chainerrorWhenNo registered deserializeUser function can handle the session data — the internal chain exhausts all registered deserializers without finding a match.Throws
Error('Failed to deserialize user out of session') — propagated via next(err) to Express error handlerRequired handlingEnsure at least one deserializeUser function handles the stored session format. This error commonly occurs after a data migration changes the user ID type or format. Add a migration deserializer that handles both old and new formats.costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[5] - authorize · authorize-strategy-errorerrorWhenThe OAuth strategy encounters an error during the authorization flow — network failure reaching the provider's token endpoint, invalid OAuth tokens, or provider returning an error response.Throws
Error propagated to the callback (if provided) as first argument, or forwarded via next(err) to Express error handler if no callbackRequired handlingCaller MUST provide a callback or mount an Express error handler. Without a callback, strategy errors go to next(err). With a callback, check err as first argument before inspecting req.account.costlowin prodimmediate exceptionusers seeauthentication failurevisibilityvisible - authorize · authorize-failure-without-redirectwarningWhenAuthorization fails (strategy calls fail()) and no failureRedirect is configured and no callback is provided.Throws
AuthenticationError with HTTP 401 status — if failWithError:true is set. Otherwise, a 401 HTTP response is sent directly with WWW-Authenticate headers.Required handlingAlways provide a failureRedirect or a callback when using authorize(). Without either, failed authorization sends a raw 401 response which may not align with the application's error handling or UI expectations.costlowin prodimmediate exceptionusers seeauthentication failurevisibilityvisible - serializeUser · serialize-chain-failureerrorWhenNo registered serializeUser function calls done with a non-falsy id — the chain exhausts without serializing a user identifier.Throws
Error('Failed to serialize user into session') — propagated to the req.logIn() callbackRequired handlingEnsure at least one serializeUser function calls done(null, someId) for every user object type your application produces. This error blocks all login attempts.costhighin prodimmediate exceptionusers seeauthentication failurevisibilityvisibleSources[5] - deserializeUser · deserialize-database-errorerrorWhenThe deserializeUser function calls done(err) due to a database failure when looking up the user by the stored ID. Because passport.session() runs on every request, this error fires on every authenticated request until the database recovers.Throws
Error propagated via next(err) on every authenticated requestRequired handlingImplement defensive error handling in the deserializer. If the database is temporarily unavailable, consider returning done(null, false) to treat the user as unauthenticated rather than crashing every request. Distinguish "user not found" (false) from "database error" (err). Add database retry logic or circuit breakers to the deserializer.costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[8] - deserializeUser · deserialize-chain-failureerrorWhenNo registered deserializeUser function can reconstruct a user from the stored session identifier — the chain exhausts without calling done with a user.Throws
Error('Failed to deserialize user out of session') — propagated on every request where a session existsRequired handlingEnsure deserializeUser handles all possible session identifier formats. After user data migrations, add a compatibility handler for old-format IDs.costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[5] - use · use-strategy-no-nameerrorWhenpassport.use(strategy) is called where the strategy object has no .name property and no name argument is provided. The name variable resolves to undefined/null/empty string.Throws
Error('Authentication strategies must have a name') — thrown synchronously during app startup (not at request time).Required handlingAlways ensure strategies have a name. Either pass an explicit name: passport.use('local', new LocalStrategy(...)), or verify the strategy package exports a .name property. Custom strategies defined as anonymous objects must be passed with an explicit name argument. This error surfaces during app initialization, crashing startup.costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[5] - initialize · initialize-order-violationerrorWhenpassport.initialize() middleware is mounted AFTER passport.session() or passport.authenticate() routes in the Express middleware stack. Because initialize() attaches req._sessionManager and compatibility shims, strategies that run before initialize() will fail with 'req.logIn is not a function' or similar TypeError when attempting session operations.Throws
TypeError: req.logIn is not a function — or similar, because the req methods were not yet attached by initialize(). Also: req._passport.instance not set causes failures in passport@0.4.x-dependent strategies.Required handlingMount passport.initialize() BEFORE passport.session() and before any routes that use passport.authenticate(). Correct order: app.use(session(...)) → app.use(passport.initialize()) → app.use(passport.session()) → routes. Incorrect middleware order is the most common passport setup bug.costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible - initialize · initialize-missing-in-compat-modeerrorWhenpassport.initialize() is omitted entirely and a strategy package was built against passport@0.4.x or earlier. Those strategies read req._passport.instance to access the Passport instance. When initialize() is not called, req._passport is undefined, causing those strategies to throw a TypeError on every request.Throws
TypeError: Cannot read properties of undefined (reading 'instance') — thrown inside the strategy's authenticate() method when it tries to access req._passport.instance.Required handlingAlways use passport.initialize() when using strategies that may depend on passport@0.4.x internals (e.g., passport-azure-ad, passport-saml, older OAuth strategies). Check the strategy's peer dependency on passport to determine if compat mode is required. When in doubt, always mount initialize().costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[10] - transformAuthInfo · transform-auth-info-database-errorwarningWhenA registered transformAuthInfo function calls done(err) due to a database failure — for example, when loading a Client record from the database using info.clientID fails because the database is unavailable or the ID is invalid.Throws
Error from done(err) propagated via next(err) to Express error handler. The original info object is NOT set on req.authInfo when a transformer errors.Required handlingThe transform function MUST call done(err) on failure, not silently swallow errors. The Express error handler will receive the error. For database-backed transforms, implement circuit breakers or fallback behavior. If client info enrichment fails non-critically, consider calling done(null, info) to pass the original info through rather than failing the entire request.costlowin prodimmediate exceptionusers seeauthentication failurevisibilityvisibleSources[5] - transformAuthInfo · transform-auth-info-chain-failurewarningWhenA registered transformAuthInfo function throws synchronously. Passport wraps the transformer call in a try/catch block and forwards the error to done(), which propagates to next(err).Throws
Error from the thrown exception, propagated via catch(e) → done(e) → next(err) to the Express error handler.Required handlingTransformer functions must not throw synchronously. Wrap async operations in try/catch and call done(err). Synchronous throws are caught but still fail the request by forwarding to the Express error handler. Ensure all code paths in the transformer either call done(err) or done(null, transformedInfo).costlowin prodimmediate exceptionusers seeauthentication failurevisibilityvisibleSources[5]
Sources
Every postcondition cites at least one of these. Numbered to match the footnotes above.
- [1]passportjs.org/docs/authenticatehttps://www.passportjs.org/docs/authenticate/
- [2]github.com/jaredhanson/passporthttps://github.com/jaredhanson/passport/blob/master/lib/middleware/authenticate.js
- [3]passportjs.org/concepts/authenticationhttps://www.passportjs.org/concepts/authentication/login/
- [4]github.com/jaredhanson/passporthttps://github.com/jaredhanson/passport/blob/master/lib/sessionmanager.js
- [5]github.com/jaredhanson/passporthttps://github.com/jaredhanson/passport/blob/master/lib/authenticator.js
- [6]github.com/jaredhanson/passporthttps://github.com/jaredhanson/passport/blob/master/lib/http/request.js
- [7]passportjs.org/concepts/authenticationhttps://www.passportjs.org/concepts/authentication/logout/
- [8]github.com/jaredhanson/passporthttps://github.com/jaredhanson/passport/blob/master/lib/strategies/session.js
- [9]passportjs.org/docs/authorizehttps://www.passportjs.org/docs/authorize/
- [10]github.com/jaredhanson/passporthttps://github.com/jaredhanson/passport/blob/master/lib/middleware/initialize.js
- [11]passportjs.org/concepts/authenticationhttps://www.passportjs.org/concepts/authentication/middleware/
Need a different package?
Request a profile