skip to content

An Express API route guarded by passport.authenticate('jwt') answers 500 'Login sessions require session support' for valid tokens only; why, and what is the fix?

level: seniorimportance: should knowfreq 35%

answer

  1. only the happy path breaks
  2. what success triggers next
  3. the option's default value
  4. who creates req.session

basics

~20 s

passport.authenticate defaults session to true, so once passport-jwt accepts the token Passport calls req.login, which needs req.session; with no session middleware it errors and the error becomes a 500. Pass { session: false } on the API route.

solid answer

~40 s

The message comes from Passport's session manager, not from token checking. After the JWT strategy succeeds, `passport.authenticate()` calls `req.login(user, options)`, and `session` defaults to `true`, so Passport tries to regenerate `req.session`, serialize the user and save. No session middleware means no `req.session`, so `req.login()` fails and the error goes to error middleware as a 500. Bad tokens fail earlier with a 401, which is why only valid ones break. The fix is `passport.authenticate('jwt', { session: false })`, ideally as one guard on the API router. Mounting express-session to silence it is worse: each API call then creates a session record and a cookie, or fails with `Failed to serialize user into session` if no serializer exists.

code

javascript · 19 lines
javascript
const express = require('express');
const passport = require('passport');
// the passport-jwt strategy is registered at startup

function sendProfile(req, res) {
  res.json({ id: req.user.id });
}

const api = express.Router();

// Wrong: session defaults to true, so a valid token makes Passport call req.login()
// api.get('/profile', passport.authenticate('jwt'), sendProfile);

// Right: one guard for the whole router, and no session work at all
api.use(passport.authenticate('jwt', { session: false }));
api.get('/profile', sendProfile);

const app = express();
app.use('/api', api);

go deeper

for a junior

Recall that passport.authenticate starts a login session by default and that API routes need { session: false } to skip it.

for a middle

Trace the success path: strategy success, req.login, the session option's default, the session manager needing req.session, then next(err).

for a senior

Explain why only valid tokens fail, why mounting express-session is the wrong fix, and how a router-level guard plus a happy-path test keeps it fixed.

for a principal

Treat it as a convention: one shared API guard owned by the platform code, so individual routes never choose the session option themselves.

## Reading the error ``Login sessions require session support. Did you forget to use `express-session` middleware?`` comes from Passport's session manager. It is raised when Passport tries to **start a login session** and `req.session` does not exist. Nothing is wrong with the token: by the time this message appears, passport-jwt has already accepted it and the verify callback has returned a user. ## What `passport.authenticate()` does after a strategy succeeds 1. The strategy calls its success action with the user. 2. Unless the route supplied a custom callback or the `assignProperty` option, Passport calls `req.login(user, options)` with the route's options. 3. `req.login()` reads `options.session`, which **defaults to `true`**. 4. With `session` true it hands off to the session manager, which regenerates `req.session`, runs `serializeUser`, writes `req.session.passport.user` and saves. 5. Step 4 needs `req.session`, which only session middleware such as express-session creates. Without it the session manager returns the error above, `req.login()` sets `req.user` back to `null`, and Passport forwards the error with `next(err)`, so the client gets a 500 from error middleware. passport-jwt being meant for use without sessions does not change this. The strategy never switches the option off; the route has to. ## Three symptoms of one omission | What the app mounts | Result of a valid token on `passport.authenticate('jwt')` | |---|---| | No session middleware | 500: `Login sessions require session support...` | | express-session, no `serializeUser` | 500: `Failed to serialize user into session` | | express-session and a serializer | 200, but each call regenerates a session, stores a record and returns a `Set-Cookie` header | The third row is the dangerous one because it looks healthy. It typically appears once express-session is mounted app-wide for a dashboard. A mobile client that discards cookies leaves one orphaned session record per request in the store, and the cookie each response carries is a full sign-in wherever `passport.session()` runs on the same path. ## Why tests often miss it Failed authentication never reaches `req.login()`. A missing, malformed, badly signed or expired token, or a verify callback that answers `done(null, false)`, ends in a 401 before any session work starts. A suite that only checks rejections stays green, and the fault appears only on the happy path, often first in production. ## Confirming the diagnosis 1. Reproduce with a token you know is valid for an existing user; a bad token proves nothing here. 2. Read the logged error's stack: it starts in Passport's session manager, called from `req.login()`, not in the JWT strategy. 3. Check the route's `passport.authenticate()` options for `session`; an absent key means `true`. 4. If the app mounts express-session somewhere, call the route with a valid token and look for a `Set-Cookie` header in the response. Its presence means the route is creating login sessions for API clients even where nothing fails. ## The fix, and keeping it fixed - Add `{ session: false }` to every `passport.authenticate('jwt', ...)` call, or better, put one guard at the top of the API router so no route can forget it. - Do **not** mount express-session app-wide to make the error go away; that turns the first row into the third. - Do not reach for `passport.initialize()`. Passport's own documentation says that since 0.6 it is typically no longer necessary, and it does not create `req.session` in any case. - Add a test that sends a **valid** token and asserts a 200 response with no `Set-Cookie` header. - If the store has already filled with orphaned records, how such records expire and get cleaned up is covered with session lifecycle and session stores. ## The same trap elsewhere The default applies to every strategy, not only passport-jwt. Any API route authenticated per request, for example with HTTP Basic credentials, needs the same `{ session: false }`, and Passport's own examples show exactly that for bearer and basic schemes.

  • Why did the route's integration tests pass?
    They most likely sent only missing or bad tokens. Those fail inside the strategy and produce a 401 before Passport ever calls `req.login()`, so the session code path was never reached. Only a request with a valid token for a real user triggers the failing step; add one, and assert there is no `Set-Cookie` header on the response.
  • Would adding passport.initialize() fix it?
    No. `passport.initialize()` attaches helpers such as `req.login` to the request, which `passport.authenticate()` already does, and Passport's documentation says it has typically been unnecessary since 0.6. It does not create `req.session`; only session middleware does. The real fix is `{ session: false }`.
  • The same app also runs express-session app-wide for its dashboard; how would the bug look there?
    With a serializer registered, the API route returns 200, so nothing looks wrong. Each call regenerates a session, saves a record with the user id and sends a `Set-Cookie` header. Cookie-less mobile clients leave one orphaned record per request, and the cookie is a working sign-in for any route on that path that runs `passport.session()`.

  • The error means the bearer token failed signature verification.
  • Adding passport.initialize() makes the error go away.
  • Mounting express-session app-wide is the right fix for the API route.
  • passport-jwt disables sessions by itself, so the option is redundant.
  • Once a serializer is registered, leaving the option off is harmless.