skip to content

Identity & Permissions

Express ships no authentication: you hand-wire a Passport strategy and a session store, or mount a library like Auth.js, better-auth or Clerk. Interviewers probe what you wired and what you gave up.

on this pageshow

explore

questions

20

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

Why is express-session's default MemoryStore unsuitable for a production Express app, and what does its startup warning mean?

level: juniorimportance: must knowfreq 62%

basics

~20 s

Without a store option, express-session keeps every session in a MemoryStore inside one Node process: abandoned sessions pile up in the heap, other processes cannot see them, and a restart wipes them, signing every user out.

open as a page

With Passport in an Express app, what do passport.use(), a strategy such as passport-local and its verify callback each do during a password login?

level: juniorimportance: must knowfreq 70%

basics

~20 s

passport.use() registers a strategy under a name and passport.authenticate('local') runs it on a route. The strategy pulls credentials out of the request; your verify callback looks the user up and reports the outcome through done().

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 express-session, what do the resave and saveUninitialized options control, and what should a login-only Express app set them to?

level: middleimportance: must knowfreq 58%

basics

~20 s

In express-session, resave writes an unchanged session back to the store on every request and saveUninitialized stores a new, untouched session and sets its cookie. Both default to true with a deprecation; a login app sets both to false.

open as a page

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?

level: middleimportance: must knowfreq 62%

basics

~20 s

done(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.

open as a page

Every deploy of an Express dashboard using express-session signs all users out; what in the session wiring causes it, and how do you fix it?

level: seniorimportance: must knowfreq 48%

basics

~20 s

Sessions die with the process when express-session runs on its default MemoryStore, and cookies stop verifying when the secret changes per deploy. Wire connect-redis RedisStore, keep the secret stable and rotate it as an array.

open as a page

With Auth.js mounted in an Express app, when are sessions an encrypted JWT cookie and when are they database rows?

level: middleimportance: should knowfreq 28%

basics

~20 s

Auth.js uses the jwt strategy, an encrypted JWT in the session cookie, unless the config has an adapter; then it defaults to database, where the cookie holds only a session token looked up in the adapter's tables. session.strategy overrides either default.

open as a page

In an Express 5 app, how do you mount Auth.js through @auth/express, and how does a protected route read the session?

level: middleimportance: should knowfreq 30%

basics

~20 s

Mount ExpressAuth(config) on a plain prefix with app.use('/auth', ...) so it serves the sign-in, callback, sign-out and session endpoints, set AUTH_SECRET, and read the user with getSession(req, config), which resolves to the session or null.

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

With Passport in an Express app, how do you write a custom API-key strategy, and what must its authenticate() method do?

level: middleimportance: should knowfreq 32%

basics

~10 s

Subclass passport.Strategy, set this.name, and implement authenticate(req, options) so that every path ends in exactly one action: this.success(user), this.fail(challenge, status), this.error(err), this.redirect(url) or this.pass(). Then register it with passport.use().

open as a page

After adding Clerk's clerkMiddleware() to an Express API, requests with no session still reach your handlers. Why, and how should you protect routes?

level: seniorimportance: should knowfreq 25%

basics

~20 s

clerkMiddleware() only reads the session token and attaches the auth state to the request; it calls next() for signed-out requests too. Protect routes with your own middleware that checks getAuth(req).userId and returns 401 when it is null.

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

In an Express 5 app, an async passport-local verify callback throws during a database outage and the whole Node process exits; why doesn't Express 5 catch it, and what is the fix?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Express 5 forwards only rejections of a promise the middleware returns. passport.authenticate returns nothing and passport-local catches only synchronous throws, so the rejection goes unhandled and Node's default throw mode exits. Catch inside verify and call done(err).

open as a page

With Passport in an Express app, how does passport-openidconnect turn a provider callback into a user, and why does passport-google-oauth20 never read the id_token?

level: seniorimportance: should knowfreq 38%

basics

~20 s

passport-openidconnect exchanges the code, checks the ID token's issuer, audience and expiry, builds the profile from its claims and calls verify(issuer, profile, cb). passport-google-oauth20, an OAuth 2.0 strategy, fetches the profile from userinfo with the access token.

open as a page

For a startup's new Express API, how would you choose between hand-wired Passport, Auth.js, better-auth and Clerk, and what does leaving each one cost?

level: principalimportance: should knowfreq 35%

basics

~20 s

Choose by who holds users and what you must build: Passport only authenticates requests, Auth.js and better-auth bring endpoints with data in your database, Clerk hosts everything. Leaving the first three is a code rewrite; leaving Clerk also migrates users.

open as a page

When you mount better-auth in an Express 5 app with toNodeHandler, where do users and sessions live, and what must exist first?

level: middleimportance: nice to knowfreq 22%

basics

~20 s

better-auth keeps users, sessions, linked accounts and verification tokens in your own database, in user, session, account and verification tables it defines; those tables must exist first, and the handler is mounted with app.all('/api/auth/*splat', toNodeHandler(auth)).

open as a page