skip to content

With Passport in an Express app, why does a dashboard sign-in that calls req.login(user, { session: false }) leave the user anonymous on the next request?

level: seniorimportance: should knowfreq 30%

answer

  1. what outlives the request
  2. the option's two branches
  3. who logs in under a custom callback
  4. logout wants a callback too

basics

~20 s

req.login always sets req.user, but only with session left at its default true does it regenerate the session, run serializeUser and save req.session.passport.user; under session: false it serializes nothing, so the login lasts one request.

solid answer

~40 s

`req.login()` sets `req.user` for the current request, then checks `options.session`. With the default `true` it needs a callback and hands off to the session manager: regenerate the session, run `serializeUser`, store the value at `req.session.passport.user`, save, then call back. With `session: false` it skips all of that, so on the next request `passport.session()` finds no login data and `req.user` stays unset. That branch is right for a token API, where every call brings its own token. A dashboard sign-in written with a custom `passport.authenticate` callback must call `req.login(user, cb)` itself with sessions on, and respond inside the callback. `req.logout()` mirrors it and, since Passport 0.6, requires a callback too.

code

javascript · 20 lines
javascript
// app, passport, express-session, passport.session() and the 'local' strategy are set up at startup
const { promisify } = require('node:util');

app.post('/dashboard/login', (req, res, next) => {
  passport.authenticate('local', (err, user, info) => {
    if (err) return next(err);
    if (!user) return res.status(401).json({ message: info?.message });
    // sessions stay on: regenerate, serializeUser, save, then respond
    req.login(user, (loginErr) => {
      if (loginErr) return next(loginErr);
      res.json({ redirect: '/dashboard' });
    });
  })(req, res, next);
});

// Express 5 forwards the rejection if the session store fails
app.post('/dashboard/logout', async (req, res) => {
  await promisify(req.logout).call(req);
  res.redirect('/dashboard/login');
});

go deeper

for a junior

Recall that req.login sets req.user and, with sessions on, stores the user so later requests see it; session: false makes it one-request only.

for a middle

Explain the steps req.login runs with sessions on, why a custom authenticate callback must call it, and that both login and logout take a callback.

for a senior

Diagnose copied session: false options, logout calls broken by the upgrade, and lost returnTo data, and know where keepSessionInfo fits.

for a principal

Set a house rule for sign-in handlers: sessions on, respond only in the callback, async handlers relying on Express 5 forwarding, and tests that cover the next request.

## What `req.login()` does Passport adds `req.login()` (alias `req.logIn()`) to the request; the signature is `req.login(user, [options], callback)`. In Passport 0.7 it does this: 1. Sets `req.user` to the user, so the rest of **this** request sees it. 2. Reads `options.session`, which defaults to `true`. 3. With `session` true, it requires a callback, throwing `req#login requires a callback function` without one, and hands off to the session manager, which: - regenerates the session, giving it a new id and dropping the pre-login contents unless `keepSessionInfo: true` is passed, - runs `serializeUser` on the user, - writes the result to `req.session.passport.user`, - saves the session, then calls your callback. 4. With `session: false`, it skips step 3 entirely and calls the callback, if one was given, straight away. ## Why the next request is anonymous On the next request `passport.session()` looks for `req.session.passport.user`. Under `session: false` nothing was ever written there, so it finds nothing, never calls `deserializeUser`, and `req.user` stays unset. The login lasted exactly one request. Traced across two requests: 1. `POST` to the sign-in route: the credentials check passes, `req.login(user, { session: false }, cb)` sets `req.user`, the callback responds with success, and the session record, if one exists, holds no `passport.user`. 2. `GET` of the next dashboard page: express-session loads that record, `passport.session()` finds no login data and passes, and the page's `req.isAuthenticated()` check sends the browser back to sign in. That is the intended behaviour on a bearer-token API, where every request brings its own token; on a session-based sign-in it is a bug, often an option copied over from the API code. ## Custom callbacks hand the login back to you Passing a callback to `passport.authenticate('local', (err, user, info) => { ... })` lets a route answer in its own format, for example JSON for a dashboard front end. The price is that Passport then does **not** log the user in: the callback receives the outcome, and calling `req.login()` becomes the route's job. The sign-in in this scenario must call `req.login(user, callback)` with sessions left on, and send its response only inside that callback, once the session has been saved. ## Logout mirrors login `req.logout()` (alias `req.logOut()`) sets `req.user` to `null`, then removes `req.session.passport.user`, saves the session and regenerates it. Since Passport 0.6 it is asynchronous and **requires a callback**; the once-common `req.logout(); res.redirect('/')` now throws `req#logout requires a callback function`. The upgrade also made login and logout regenerate the session by default, which is why data parked in the anonymous session, such as `req.session.returnTo`, disappears at sign-in unless `keepSessionInfo: true` is passed. ## Calling them from an Express 5 handler Both functions take callbacks, but an Express 5 route handler may be `async`. Wrap the call with `util.promisify` and `await` it. Express 5 forwards a rejected promise from a handler to error middleware, so a session-store failure during sign-in or sign-out becomes an ordinary error response without an explicit `next(err)`. Under Express 4 the same `await` needed a `try`/`catch` that called `next(err)`. ## Reference | Call | Session writes | Callback | |---|---|---| | `req.login(user, cb)` | Regenerate, serialize, save | Required | | `req.login(user, { session: false }, cb)` | None | Optional | | `req.login(user, { keepSessionInfo: true }, cb)` | Regenerate keeping prior data, serialize, save | Required | | `req.logout(cb)` | Remove the user, save, regenerate | Required | Points worth saying aloud in an interview: - `req.login()` always sets `req.user`; the `session` option only decides whether anything outlives the request. - `passport.authenticate()` calls `req.login()` for you unless you pass a custom callback or `assignProperty`. - Respond inside the callback, never right after the call, or the browser may follow a redirect before the session is saved. Why a server should issue a new session identifier at sign-in and sign-out is covered with session lifecycle; Passport's contribution is that it does so by default.

  • After a Passport upgrade, sign-out throws 'req#logout requires a callback function'; what changed?
    Since Passport 0.6, `req.logout()` is asynchronous: it removes the login data, saves the session and regenerates it, and only then calls back. Code written as `req.logout(); res.redirect('/')` must become `req.logout((err) => { if (err) return next(err); res.redirect('/'); })`, or an awaited promisified call in an Express 5 async handler.
  • After sign-in, users are no longer sent back to the page they first requested; the code reads req.session.returnTo. Why?
    Since 0.6, `req.login()` regenerates the session and drops its earlier contents by default, so the `returnTo` value saved while anonymous is gone. Pass `keepSessionInfo: true` to `passport.authenticate()` or `req.login()`, and Passport merges the earlier session data into the regenerated one; `successReturnToOrRedirect` then finds the stored URL.
  • When is req.login(user, { session: false }) the right call?
    When the request needs `req.user` but nothing should persist: a token API's sign-in route that verifies credentials and then issues a token in the same response, or a handler that authenticates by some other means mid-request. It is exactly what `passport.authenticate()` does internally when a route passes `{ session: false }`.

  • req.login(user, { session: false }) still writes the user id into the session.
  • A custom passport.authenticate callback logs the user in automatically.
  • req.login's callback is optional when sessions are on.
  • Calling req.logout() and redirecting on the next line is fine in current Passport.
  • Sign-in keeps everything the anonymous session held unless told otherwise.

Assumes Express 5, which forwards a rejected promise from an async handler to error middleware; under Express 4 the awaited logout needed a try/catch calling next(err).