skip to content

Session vs Token Mode

The same library backs a classic session app and a stateless API, and the switch is two serialization hooks plus an option. Calling req.login under session: false serializes nothing at all.

on this pageshow

questions

5

With Passport and passport-jwt in an Express API, how do you protect a route with a bearer token from the Authorization header?

level: juniorimportance: must knowfreq 60%

answer

  1. a strategy registered once
  2. where the token is read from
  3. bearer-scheme extractor factory
  4. secret or public key plus verify
  5. no login session on the route

basics

~10 s

Register a passport-jwt JwtStrategy with jwtFromRequest set to ExtractJwt.fromAuthHeaderAsBearerToken() and a secretOrKey, map the verified payload to a user in its verify callback, then guard routes with passport.authenticate('jwt', { session: false }).

solid answer

~40 s

I register `new JwtStrategy(options, verify)` with `passport.use`. The options say where the token comes from, `jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()`, which reads `Authorization: Bearer <token>` with the scheme matched case-insensitively, and how to check it: `secretOrKey` (a shared secret or a PEM public key) or `secretOrKeyProvider`, plus `issuer`, `audience` and `algorithms` to pin. The strategy verifies the token before my `verify(payload, done)` runs, so the callback only maps `payload.sub` to a user and calls `done(null, user)` or `done(null, false)`. The route gets `passport.authenticate('jwt', { session: false })`: a missing, bad or expired token, or `done(null, false)`, ends in a plain 401, and on success `req.user` holds the user for that request only.

code

javascript · 21 lines
javascript
const express = require('express');
const passport = require('passport');
const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');

async function findUserById(id) {
  // look the user up in your data layer; resolve undefined when absent
}

passport.use(new JwtStrategy({
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey: process.env.JWT_SECRET,
  algorithms: ['HS256'],
}, (payload, done) => {
  findUserById(payload.sub).then((user) => done(null, user || false), done);
}));

const app = express();

app.get('/api/profile',
  passport.authenticate('jwt', { session: false }),
  (req, res) => res.json({ id: req.user.id }));

go deeper

for a junior

Recall the three pieces: JwtStrategy with jwtFromRequest and secretOrKey, a verify callback that maps the payload to a user, and passport.authenticate('jwt', { session: false }) on the route.

for a middle

Explain the order: extract, verify signature and expiry, only then the verify callback. Know which outcomes become a 401 and which reach error middleware.

for a senior

Show you would pin algorithms, issuer and audience, keep the token out of URLs, use failWithError for a consistent error body, and guard a whole router so no route forgets the option.

for a principal

Frame the trade-off: per-request token checks keep the API stateless and horizontally simple, but revocation and key rotation now live with the token issuer, so ask who owns those.

## What passport-jwt adds to Passport **Passport** is authentication middleware for Express that delegates each way of signing in to a **strategy**. **passport-jwt** is the strategy for a **JSON Web Token** (JWT) that the client sends with every request. Its README describes it as intended for securing RESTful endpoints **without sessions**: the client presents the token each time, and the server keeps no login state between requests. You build it with `new JwtStrategy(options, verify)` and register it with `passport.use()`. It registers itself under the name `'jwt'`, which is the name `passport.authenticate()` takes. ## The options that matter | Option | What it does | |---|---| | `jwtFromRequest` | Required. A function that takes the request and returns the raw token string or `null` | | `secretOrKey` | A shared secret or a PEM-encoded public key used to check the signature | | `secretOrKeyProvider` | A callback `(request, rawJwtToken, done)` that supplies the key per request; use it instead of `secretOrKey`, never together | | `issuer`, `audience`, `algorithms` | Passed to the verifier, which then checks the token's `iss` and `aud` and accepts only the listed algorithms | | `passReqToCallback` | When `true`, the verify callback receives `(req, payload, done)` | The constructor throws a `TypeError` when the key or `jwtFromRequest` is missing, so a misconfigured strategy fails when the app boots rather than on the first request. `ExtractJwt.fromAuthHeaderAsBearerToken()` reads the `Authorization` header and returns its value only when the scheme is `bearer`, compared case-insensitively, so `Bearer abc` and `bearer abc` both work. A header with another scheme, such as `JWT abc`, yields no token. The other factories on `ExtractJwt` are `fromHeader(name)`, `fromBodyField(name)`, `fromUrlQueryParameter(name)`, `fromAuthHeaderWithScheme(scheme)` and `fromExtractors([...])`, which tries several extractors in order. ## What happens on each request 1. `passport.authenticate('jwt', { session: false })` runs the strategy. 2. The extractor pulls the token out of the request. No token means the attempt fails. 3. The strategy obtains the key and verifies the token's signature and claims, including expiry. Any failure here, such as a wrong signature, an expired token or a wrong issuer, fails the attempt. 4. Only then does your **verify callback** run, with the decoded payload. It looks the user up, typically from `payload.sub`, and calls `done`. 5. On success Passport sets `req.user` and calls `next()`, so the route handler runs. ## Outcomes and what the client sees | Situation | Result | |---|---| | Header missing, wrong scheme, bad signature, expired token | 401 with the body `Unauthorized`; the verify callback never runs | | `done(null, false)`, no such user | 401 with the body `Unauthorized` | | `done(err)`, the lookup itself failed | the error goes to error middleware through `next(err)` | | `done(null, user)` | `req.user` is set and the handler runs | passport-jwt reports its failures with an error object rather than a challenge string, so Passport sets no `WWW-Authenticate` header on these 401 responses. To answer in your API's own error format, add `failWithError: true`: Passport then hands an `AuthenticationError` whose `status` is 401 to your error middleware instead of ending the response itself. ## Why `{ session: false }` belongs on the route `passport.authenticate()` defaults its `session` option to `true`. On success it would then call `req.login()` to store the user in a server-side session, which an API that receives a token on every call does not want, and which fails outright when no session middleware is mounted. With `session: false`, `req.user` lives for the current request only, and the next request has to bring its token again. ## Common mistakes - Decoding or verifying the token again inside the verify callback: the strategy has already done both before the callback runs. - Leaving `{ session: false }` off an API route. - Not pinning `algorithms`, `issuer` and `audience` when you know who issues the tokens; what each claim check defends against is covered with JWT validation. - Reading the token from the query string for convenience: URLs end up in access logs and browser history.

  • What does the client receive when the token is missing or expired, and how do you return your own error body instead?
    A 401 whose body is the plain word `Unauthorized`, with no `WWW-Authenticate` header, because passport-jwt fails with an error object rather than a challenge string. Add `failWithError: true` to `passport.authenticate()` and Passport passes an `AuthenticationError` with `status` 401 to error middleware, which can then render the API's usual error JSON.
  • During a client migration some requests carry the token in a custom header instead; how do you accept both?
    Combine extractors with `ExtractJwt.fromExtractors([ExtractJwt.fromAuthHeaderAsBearerToken(), ExtractJwt.fromHeader('x-access-token')])`; they are tried in order until one returns a token. Name the header in lower case, because Node exposes incoming header names lower-cased, and note that `fromHeader` returns the whole header value, so that header must carry the bare token.
  • Why would you use secretOrKeyProvider instead of secretOrKey?
    When the key is not one fixed value: the issuer signs with rotating asymmetric keys, or different tenants use different keys. `secretOrKeyProvider(request, rawJwtToken, done)` runs per request and calls `done(null, key)`; decoding the token's header to pick the key is up to you. Passing both options makes the constructor throw.

  • The verify callback must decode the token and check its signature itself.
  • passport-jwt turns sessions off by itself because tokens are stateless.
  • fromAuthHeaderAsBearerToken also finds the token in cookies or the query string.
  • Calling done(null, false) in the verify callback produces a 500 error.
  • The strategy is registered under the name 'bearer'.
open as a page

With Passport in an Express app, what do serializeUser and deserializeUser each do, and when does each one run?

level: middleimportance: must knowfreq 62%

basics

~10 s

serializeUser runs once at login and picks what Passport stores in the session, usually the user id at req.session.passport.user; deserializeUser runs on each request through passport.session() and turns that value back into req.user.

open as a page

In one Express codebase serving a session-based dashboard and a bearer-token mobile API, how do you wire Passport for both?

level: middleimportance: should knowfreq 45%

basics

~10 s

Mount express-session and passport.session() only on the dashboard's router, register the sign-in strategy, the passport-jwt strategy and both serialization hooks once, and guard the API router with passport.authenticate('jwt', { session: false }).

open as a page

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%

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.

open as a page

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%

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.

open as a page