skip to content

Express.js

The minimal Node framework: an ordered middleware stack, routers and thin request and response helpers, now on version 5. Interviewers use it because whatever it leaves to you, you must explain.

on this pageshow

explore

questions

page 1 of 2

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

In Express 5, how does Express recognise an error-handling middleware function, and why must it be registered after the routes?

level: juniorimportance: must knowfreq 76%

basics

~20 s

Express treats a middleware function as an error handler only when it declares exactly four parameters, (err, req, res, next). Errors travel forward through the stack, so it must be registered after the routes and middleware whose errors it should catch.

open as a page

In Express 5, what must every (req, res, next) middleware do, and why does a request hang when one neither responds nor calls next()?

level: juniorimportance: must knowfreq 78%

basics

~20 s

Express middleware must either end the request-response cycle with a response or call next() to pass control on. Doing neither leaves the request hanging: Express has no fallback reply and no response timeout, so the client waits until something else gives up.

open as a page

In an Express 5 route handler, where do req.params, req.query and req.body get their values, and why can req.body be undefined?

level: juniorimportance: must knowfreq 72%

basics

~10 s

req.params holds the named route parameters, req.query the parsed query string, and req.body the payload. In Express 5 req.body stays undefined until a parser such as express.json() runs and the request's Content-Type matches it.

open as a page

In Express 5, what do app.METHOD, app.all and app.route register, and which handler answers when two registered routes match one request?

level: juniorimportance: must knowfreq 62%

basics

~20 s

app.get, app.post and the other app.METHOD calls register a handler for one HTTP method and path, app.all for every method, and app.route chains several methods on one path. Express runs the first registered route that matches.

open as a page

With Supertest against an Express app, how do chained .expect calls assert status, headers and body, and what does each form compare?

level: juniorimportance: must knowfreq 58%

basics

~20 s

Supertest's .expect picks its check from the arguments: a number asserts the status, a field and a value assert a header, and a string, RegExp or object asserts the body. Checks run in the order written and the first failure is reported.

open as a page

When testing an Express 5 app with Supertest, why does app.js export the app and leave app.listen to a separate entry file?

level: juniorimportance: must knowfreq 62%

basics

~20 s

Supertest's request(app) takes the Express app, a plain request-handler function, and runs it on its own server on an ephemeral port, closed afterwards. An app module that calls listen grabs a fixed port at import and keeps the test process from exiting.

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

In an Express 5 checkout route, which failures reach error middleware by themselves, and which still need an explicit next(err)?

level: middleimportance: must knowfreq 80%

basics

~20 s

In Express 5, synchronous throws, async-function throws and rejections of a returned promise reach error middleware automatically. Callback errors, un-returned promise chains and timer callbacks do not: pass them to next(err), or the request hangs or the process crashes.

open as a page

In Express 5, what does the trust proxy setting change, and how do false, true, a hop count and a subnet list derive req.ip?

level: middleimportance: must knowfreq 62%

basics

~20 s

Express's trust proxy setting decides which X-Forwarded-* headers to believe. At the default false, req.ip is the socket peer, usually the balancer; true takes the client-writable leftmost X-Forwarded-For entry; a hop count or subnet list walks right to left past trusted proxies.

open as a page

In Express 5, how do you organise an orders API as one express.Router per resource, mounted under a /v1 prefix?

level: middleimportance: must knowfreq 70%

basics

~20 s

Give each resource its own express.Router with paths relative to its mount, mount those routers on a v1 router, and mount that once with app.use('/v1', v1), so each prefix is written in exactly one place.

open as a page

In Express 5, how do you write a reusable validation middleware that wraps a schema and keeps invalid input away from route handlers?

level: middleimportance: must knowfreq 65%

basics

~20 s

Write a factory that takes a schema and returns (req, res, next) middleware: parse the input, stop with a 400 or next(err) on failure, store the parsed result and call next() on success, mounted after express.json and before the handler.

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

An Express 5 API mounts auth, then cors, then morgan, then express.json, so preflights get 401, rejected calls go unlogged and auth sees no body; what order fixes it?

level: seniorimportance: must knowfreq 62%

basics

~20 s

Express runs app.use middleware in registration order, so mount morgan first, then helmet and cors, then express.json, then auth, then routes. Preflights are then answered before auth, 401s get logged, and auth reads a parsed req.body.

open as a page

An Express 5 API behind a load balancer mounts express-rate-limit, and soon all users get 429 together; why, and what is the right fix?

level: seniorimportance: must knowfreq 52%

basics

~20 s

express-rate-limit keys clients by req.ip, and with Express's default trust proxy false that is the load balancer's address, so every user shares one bucket. Set app.set('trust proxy', 1) or the balancer's subnet, never true, which lets clients forge X-Forwarded-For.

open as a page

In Express, how do res.locals and app.locals differ, and which one should middleware use to pass the signed-in user downstream?

level: juniorimportance: should knowfreq 42%

basics

~20 s

res.locals is a fresh object for each request and is discarded when that request ends; app.locals lives as long as the application and every request shares it. Per-request data such as the signed-in user goes on res.locals, app-wide constants and helpers on app.locals.

open as a page

In an Express 5 app, what does app.use(helmet()) do by default, and what does it not protect you from?

level: juniorimportance: should knowfreq 55%

basics

~10 s

Helmet is middleware that sets security-related HTTP response headers, such as a strict Content-Security-Policy, Strict-Transport-Security and X-Content-Type-Options: nosniff, and removes X-Powered-By. It only instructs browsers; it does not validate, authenticate or configure CORS.

open as a page

In an Express 5 JSON API, why does an unmatched route return an HTML 'Cannot GET' page, and how do you send a JSON 404?

level: juniorimportance: should knowfreq 55%

basics

~10 s

When no middleware or route responds, Express's final handler sends a 404 HTML page reading Cannot GET /path. Register app.use((req, res) => res.status(404).json(...)) after every router so unmatched requests get JSON.

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

In Express 5, how does the built-in default error handler choose the status, headers and body for an error nothing else handled?

level: middleimportance: should knowfreq 52%

basics

~20 s

Express's default handler uses err.status or err.statusCode when it is from 400 to 599, else a 4xx or 5xx res.statusCode, else 500. It sends an HTML page holding err.stack, or only the status message when the env setting is 'production'.

open as a page

In Express, when a router is mounted with app.use('/admin', adminRouter), what do req.url, req.baseUrl, req.path and req.originalUrl hold inside it?

level: middleimportance: should knowfreq 55%

basics

~10 s

Inside a router mounted at /admin, Express strips the mount path from req.url and records it in req.baseUrl. For GET /admin/users/7?sort=desc, req.url is /users/7?sort=desc, req.path /users/7, req.baseUrl /admin, and req.originalUrl stays /admin/users/7?sort=desc.

open as a page

With the cors package in an Express 5 API, how do the origin and credentials options combine for a browser frontend that sends cookies?

level: middleimportance: should knowfreq 50%

basics

~20 s

In an Express 5 API, cors({ credentials: true }) alone still sends Access-Control-Allow-Origin: *, which browsers refuse on cookie-carrying requests. Set origin to the exact frontend origin, an array, a RegExp or a callback, so a matched origin is echoed.

open as a page

showing 1–30 of 58