In a Passport verify callback in an Express app, what do done(err), done(null, false, info) and done(null, user) each tell Passport to do?
answer
- three outcomes, three strategy actions
- error versus fail versus success
- default 401, or failureRedirect
- info carries the message
basics
~20 sdone(err) is an internal error that Passport hands to next(err); done(null, false, info) is a failed login that ends in a 401, a failureRedirect or the next strategy; done(null, user) is a success that logs the user in.
solid answer
~40 sThe verify callback's `done` maps onto three strategy actions. `done(err)` becomes `this.error(err)`: Passport calls `next(err)` and your Express error middleware answers, typically with a 500. `done(null, false, info)` becomes `this.fail(info)`: Passport tries the next strategy if you passed an array, and when all have failed it applies `failureMessage` or `failureFlash`, follows `failureRedirect`, or by default answers **401 Unauthorized**. With `failWithError: true` it calls `next()` with an `AuthenticationError` instead. `done(null, user, info)` becomes `this.success(user, info)`: Passport logs the user in, sets `req.user`, then follows `successRedirect` or calls `next()`. If you pass a custom callback to `passport.authenticate()`, Passport skips all of this and hands you `(err, user, info, status)`, and logging in and responding become your job.
code
javascript · 12 linesapp.post('/api/login', express.json(), (req, res, next) => {
passport.authenticate('local', (err, user, info, status) => {
if (err) return next(err);
if (!user) {
return res.status(status ?? 401).json({ error: info?.message ?? 'Unauthorized' });
}
req.login(user, (loginErr) => {
if (loginErr) return next(loginErr);
res.json({ id: user.id });
});
})(req, res, next);
});go deeper
Recall the three shapes: an error, a false user with a message, and a user, and that a false user means a wrong password rather than a crash.
Walk through what authenticate() does for each: next(err), the failure options and the default 401, and req.login on success, plus what a custom callback changes.
Explain why misreporting an outage as a failure hides incidents and confuses users, and how failWithError or a custom callback fits a JSON API's error format.
Set a team rule for verify callbacks: one generic failure message, errors always through done(err), and one shared error format, so every strategy reports alike.
## One contract behind every strategy Every Passport strategy ends a request by calling exactly one **action** that Passport attached to it for that request: `success`, `fail`, `error`, `redirect` or `pass`. Strategies that check credentials hand the decision to the application through the **verify callback**, and the verify callback reports back through `done`. In `passport-local` the wiring is short enough to read in full: 1. If `done` received an error, the strategy calls `this.error(err)`. 2. If it received no user (`false`), the strategy calls `this.fail(info)`. 3. Otherwise it calls `this.success(user, info)`. So the three shapes of `done` are not conventions; each selects a different branch inside `passport.authenticate()`. That is also why the contract is the same for `passport-openidconnect`, the Google strategy and any custom strategy. ## The three outcomes side by side | `done` call | Strategy action | Default result | Options that change it | |---|---|---|---| | `done(err)` | `error(err)` | `next(err)`, your error middleware answers | none; a custom callback receives `err` | | `done(null, false, info)` | `fail(info)` | 401 with body `Unauthorized` | `failureRedirect`, `failureMessage`, `failureFlash`, `failWithError` | | `done(null, user, info)` | `success(user, info)` | log in, set `req.user`, `next()` | `successRedirect`, `successMessage`, `session`, `assignProperty` | ## `done(err)`: something broke An error means the check could not be carried out: the user table is unreachable, the hash library threw. Passport does not turn this into a login failure. Without a custom callback it calls `next(err)`, so the request skips the remaining route handlers and reaches the app's four-argument error middleware, which usually logs it and answers 500. In a chain of strategies an error **halts the chain**; the next strategy is not tried. ## `done(null, false, info)`: the credentials were wrong A failure is an expected outcome. Passport records it and moves on: - If `passport.authenticate()` received an **array** of strategy names, the next one is tried; only when every strategy has failed does Passport respond. - `failureMessage: true` pushes `info.message` into `req.session.messages`, which requires session support; `failureFlash` does the same through a flash helper. - `failureRedirect: '/login'` redirects the browser there. - With none of these, Passport sets the status to the strategy's status or **401**, adds a `WWW-Authenticate` header for a 401 when the strategy supplied a challenge string, and ends the response with the status text. - `failWithError: true` replaces that last step with `next()` and an `AuthenticationError` whose `status` is set, so your error middleware can format the 401. A strategy can fail with its own status: `passport-local` fails with **400** when the fields are missing, before your verify callback is ever called. ## `done(null, user, info)`: the user is known Success hands the user to Passport, which calls `req.login()` (also spelled `req.logIn`) to set `req.user` and, by default, establish a login session; with `session: false` it only sets `req.user`. The `info` object is passed through `transformAuthInfo` and lands on `req.authInfo`. Then `successRedirect` is followed or `next()` calls the route handler. With `assignProperty: 'account'`, the user is stored on `req.account` instead and no login happens; `passport.authorize()` uses this to link a third-party account to someone already signed in. ## The custom callback takes over all three Passing a function as the last argument to `passport.authenticate()` replaces the built-in handling: ```js passport.authenticate('local', (err, user, info, status) => { // err, or user === false with info and status, or a user })(req, res, next); ``` Passport calls it with `(err)`, `(null, false, info, status)` or `(null, user, info)`. Its own documentation is explicit that it then becomes the application's responsibility to log the user in and respond. Forgetting `req.login()` in this callback is the classic reason a user who just authenticated is anonymous on the next request. `status` is only present for failures that carried one, such as the 400 for missing fields; a plain wrong password arrives with no status, so default it to 401 yourself. ## Choosing the right call in your verify callback - Wrong password or unknown user: `done(null, false, { message: 'Incorrect username or password.' })`. Use one message for both, so the response does not reveal which usernames exist. - Account locked or not yet verified: still a failure, with a message saying so. - Database or network failure: `done(err)`, never `done(null, false)`. - Exactly one call per attempt: calling `done` twice makes Passport try to answer twice.
- What happens when the verify callback calls done(err) and authenticate() was given an array of strategies?The chain stops. Passport's authenticate middleware tries strategies in order and moves on only after a failure; the first strategy to succeed, redirect or error halts the chain. The error goes to `next(err)`, or to the custom callback if there is one, and the remaining strategies are never tried.
- How do you return a JSON 401 body for failed logins without writing a custom callback?Set `failWithError: true` on `passport.authenticate()`. When every strategy has failed, Passport calls `next()` with an `AuthenticationError` whose `status` is 401 (or the strategy's own status) instead of ending the response. A four-argument error middleware can then read `err.status` and send the JSON body your API uses.
- Where does the info object from done(null, user, info) end up on success?Passport passes it through `transformAuthInfo` and stores the result on `req.authInfo`, which the route handler can read, for example a scope or the method used. Since Passport 0.7 this also happens when `assignProperty` is used, unless `authInfo: false` is set.
- done(null, false) and done(err) both mean the login failed
- A database error should be reported as done(null, false)
- With a custom callback Passport still logs the user in for you
- Passport answers a failed login with 403 Forbidden by default
- Throwing inside the verify callback is the way to reject a password