PrepStack › Backend › Express.js

Express.js interview cheat sheet

Routing, the middleware chain, errors, Express 5, auth, security and production

Express questions are really questions about the middleware chain: what next() does, why order matters, how errors travel to a 4-argument handler, and what changed for async code in Express 5. After that, interviewers move to real-app concerns: validation, JWT vs sessions, helmet/CORS/rate limiting, project layering, testing with supertest and running behind a reverse proxy. Read the 15-minute revision first, then use Quiz mode and answer out loud.

15-minute revision

  1. Express is a minimal, unopinionated web framework on top of Node's http module. An app is just a (req, res) function plus a router and a stack of middleware.
  2. Middleware signature is (req, res, next). Each one must end the response or call next(), otherwise the request hangs.
  3. Middleware and routes run in the order they are registered. Body parsers, CORS and auth go before routes; the 404 handler and error handler go last.
  4. An error handler has 4 parameters (err, req, res, next). Express detects it by fn.length, so you must keep all four even if next is unused.
  5. next() goes to the next matching layer, next('route') skips the remaining handlers of the current route, next('router') leaves the router, and next(err) jumps to error handlers.
  6. Express 4 does not catch rejected promises from async handlers; you need try/catch + next(err) or a wrapper. Express 5 forwards a rejected promise to the error handler automatically.
  7. req.params = path segments (/users/:id), req.query = query string, req.body = parsed body (needs express.json() or express.urlencoded()). All values arrive as strings (except a JSON body).
  8. express.Router() is a mini-app with its own middleware and routes. Mount it with app.use('/api/users', router). Use mergeParams: true to see parent params.
  9. Express 5 path syntax (path-to-regexp v8): wildcards need a name (/*splat), optional parts use braces (/:file{.:ext}), and regex characters in strings are not allowed.
  10. Express 5 removed app.del, req.param(), res.send(status), res.json(obj, status), res.sendfile and res.redirect('back'). It needs Node 18+.
  11. Validate every input at the edge (zod, joi or express-validator) and pass only the validated, whitelisted data on to services.
  12. JWT = stateless signed token, hard to revoke. Session = server-side state + cookie id, easy to revoke but needs a shared store (Redis) when you scale out.
  13. Security baseline: helmet(), a strict cors() allow-list, express-rate-limit, body size limits, app.disable('x-powered-by') (helmet already removes it), and parameterised DB queries.
  14. Production: NODE_ENV=production, a structured logger (pino), a reverse proxy for TLS/gzip, app.set('trust proxy', 1) so req.ip and req.secure are correct, and one process per core (cluster/PM2/containers).
  15. Test with supertest: export the app without calling listen(), then request(app).get('/users').expect(200).
  16. Express = minimal and flexible; Fastify = faster, schema-based validation and serialisation, plugin encapsulation; NestJS = opinionated TypeScript framework with DI that runs on Express or Fastify.

Express basics & routing

What Express is (and isn't)

A thin layer over Node's http server that adds routing, middleware and helper methods on req/res.

  • Node's http.createServer((req, res) => ...) gives you one callback for every request. You have to parse URLs, bodies and route by hand.
  • Express adds a router (method + path matching), a middleware pipeline, and helpers like res.json(), res.status() and req.query.
  • It is unopinionated: no ORM, no folder layout, no DI and no validation built in. You choose the libraries.
  • const app = express() returns a function (req, res, next). app.listen(port) is just http.createServer(app).listen(port), so you can also pass app to an https server.
  • Current major version is Express 5 (needs Node 18+). Express 4 is still everywhere in existing code, so know both.

Interview questions

  • What is Express.js and why use it over plain Node http?
  • What does express() return?
  • Is Express opinionated? What does that mean for a project?

Routing: methods, params, query & route chaining

A route is method + path + one or more handlers; params come from the path and query values from the URL.

  • app.get/post/put/patch/delete(path, ...handlers). app.all() matches every method. A route matches only if both method and path match.
  • Route params: /users/:id puts the segment in req.params.id. Values are always strings, so convert and validate them.
  • Query string: /search?q=js&page=2 gives req.query.q and req.query.page, again as strings (or arrays for repeated keys).
  • Route chaining: app.route('/books').get(list).post(create) keeps all methods for one path together and avoids typos.
  • A route can take several handlers (app.get('/x', auth, load, send)); they behave like middleware for that route only.
  • Routes are checked in order, so put specific paths (/users/me) before generic ones (/users/:id).

Interview questions

  • Difference between req.params, req.query and req.body?
  • What is route chaining with app.route()?
  • Why does GET /users/me return "user not found" in my app?

express.Router & modular routes

express.Router() is a mini-app you mount under a path prefix to split routes by feature.

  • A Router has its own use(), get(), param() and so on, but no listen() or settings. It is "middleware and routes only".
  • Mount it with app.use('/api/users', usersRouter). Inside, paths are relative to the mount point (router.get('/:id')).
  • Router-level middleware (router.use(auth)) runs only for requests that reach that router.
  • Params from the mount path are hidden by default. Create the router with express.Router({ mergeParams: true }) to read req.params of the parent.
  • Inside a mounted router, req.baseUrl is the mount path, req.path is the rest, and req.originalUrl is the full original URL.

Interview questions

  • What is express.Router and why use it?
  • Difference between app and a Router?
  • What does mergeParams do?

Request & response objects

req and res are Node's objects extended with helpers; send exactly one response per request.

  • Useful req fields: params, query, body, headers, get(name), method, path, originalUrl, ip, hostname, protocol, secure, cookies (with cookie-parser).
  • Useful res methods: status(), json(), send(), sendStatus(), set(), cookie(), clearCookie(), redirect(), sendFile(), download(), render(), end().
  • res.status() and res.set() return res, so you can chain: res.status(201).json(user).
  • res.json() serialises with JSON.stringify and sets Content-Type: application/json. res.send() guesses the type from its argument.
  • res.locals holds data for the current request only (e.g. the logged-in user for views). app.locals lives for the whole app.
  • Send one response. A second res.json() throws ERR_HTTP_HEADERS_SENT. Check res.headersSent when unsure.

Interview questions

  • Difference between res.send(), res.json() and res.end()?
  • What causes "Cannot set headers after they are sent to the client"?
  • Difference between res.locals and app.locals?

Middleware

Middleware & the next() chain

Middleware is a function (req, res, next) that runs in registration order and either responds or calls next().

  • Middleware can run code, change req/res (e.g. set req.user), end the cycle by responding, or call next().
  • If it does neither, the request hangs until the client times out.
  • app.use(fn) runs for every method and every path; app.use('/api', fn) runs for paths that start with /api (prefix match).
  • Order is everything: a logger registered after a route never sees requests that route answered.
  • Calling next(err) (any argument except 'route' or 'router') skips all normal middleware and goes to the error handlers.
  • A sync throw inside middleware is caught by Express and treated like next(err).

Interview questions

  • What is middleware in Express?
  • What happens if a middleware neither responds nor calls next()?
  • Why does middleware order matter? Give an example.
  • How would you measure how long each request takes?

Middleware types & next('route') / next(err)

Five kinds: application-level, router-level, error-handling, built-in and third-party. next has four forms.

  • Application-level: bound to app with app.use() or app.METHOD().
  • Router-level: same, but bound to an express.Router() instance, so it only runs for that router.
  • Error-handling: four arguments (err, req, res, next), registered after routes.
  • Built-in: express.json(), express.urlencoded(), express.static(), express.raw() and express.text().
  • Third-party: from npm, e.g. helmet, cors, morgan, cookie-parser, express-session, compression.
  • Configurable middleware is just a factory that returns middleware: const requireRole = role => (req, res, next) => ....

Interview questions

  • What are the types of middleware in Express?
  • Difference between next(), next('route') and next(err)?
  • Difference between app.use('/api', fn) and app.get('/api', fn)?
  • How would you apply middleware to all routes except a few?

Body parsing & static files

express.json() and express.urlencoded() fill req.body; express.static() serves files from a folder.

  • express.json() parses bodies whose Content-Type is JSON. Other types are skipped, so req.body stays undefined in Express 5 (it was {} in Express 4).
  • express.urlencoded() parses HTML form posts. In Express 5 extended defaults to false (simple querystring); set extended: true for nested objects via qs.
  • Both have a limit option (default 100kb). Bodies above it get 413 Payload Too Large; invalid JSON gives 400.
  • File uploads (multipart/form-data) are not handled by Express; use multer or busboy.
  • express.static('public', opts) serves files with correct type, ETag and Cache-Control (maxAge). It calls next() if the file isn't found.
  • Express 5 static: dotfiles defaults to 'ignore', which also hides dot-directories like .well-known unless you allow them.

Interview questions

  • Why is req.body undefined in my POST route?
  • Difference between express.json() and express.urlencoded()?
  • How do you handle file uploads in Express?
  • How does express.static work and how would you serve a React build?

Errors & Express 5

Error-handling middleware

Errors go to middleware with four parameters, registered last; one central handler formats every error.

  • Signature (err, req, res, next). Express checks the function's arity (fn.length === 4), so you must declare all four parameters.
  • Register error handlers after all routes and the 404 handler. You can chain several (log, then respond).
  • Errors reach it via next(err), a sync throw, or (Express 5) a rejected promise from a handler.
  • A 404 is not an error to Express: if no route matches, add a normal catch-all middleware at the end that returns 404.
  • If res.headersSent is true (e.g. a stream failed halfway), call next(err) so the default handler closes the connection.
  • The default handler returns 500 with the stack trace in development, and hides the stack when NODE_ENV=production.

Interview questions

  • How do you define error-handling middleware in Express?
  • How do you handle 404s in Express?
  • Why check res.headersSent in an error handler?
  • How do you design a consistent API error format?

Async errors: Express 4 vs Express 5

Express 4 ignores rejected promises from handlers; Express 5 forwards them to the error handler.

  • In Express 4, a sync throw is caught, but an error thrown inside an async function becomes a rejected promise that Express never looks at.
  • Result in Express 4: no response (the request hangs) and an unhandledRejection, which crashes the process on modern Node by default.
  • Express 4 fixes: try/catch + next(err) in every handler, a wrapper like asyncHandler(fn), or the express-async-errors patch package.
  • In Express 5, if a handler or middleware returns a rejected promise, Express calls next(err) with the rejection value for you.
  • Express 5 still cannot see errors in callbacks that aren't returned (setTimeout, old-style fs.readFile(cb), event emitters). Pass those to next(err) yourself.
  • Errors raised in a stream's 'error' event must also be forwarded manually, or use stream.pipeline with a callback that calls next.

Interview questions

  • What happens when an async route handler throws in Express 4?
  • How did Express 5 change async error handling?
  • Write an asyncHandler wrapper and explain it.
  • In Express 5, are there errors that still won't reach the error handler?

Express 5 changes

Express 5 keeps the same API but modernises path syntax, async errors and defaults, and removes old signatures.

  • Requires Node 18+. Stable since late 2024; npm install express now installs v5.
  • Uses path-to-regexp v8: named wildcards (/*splat, or /{*splat} to also match /), braces for optional parts (/:file{.:ext}), no ?, +, * or () regex syntax inside string paths.
  • Reserved characters ()[]?+! must be escaped with \ in paths. Use an array of paths or a real RegExp object instead of inline regex.
  • req.params has a null prototype for string paths, wildcard values are arrays of segments, and unmatched optional params are omitted.
  • req.query is now a getter (not writable) and uses the simple parser by default; req.body is undefined when not parsed; urlencoded extended defaults to false.
  • res.status() only accepts integers 100–999; app.listen passes server errors (like EADDRINUSE) to its callback; body parsers support Brotli.

Interview questions

  • What are the main changes in Express 5?
  • How do you write a catch-all route in Express 5?
  • How would you migrate a large Express 4 app to Express 5?
  • Why is req.params a null-prototype object in Express 5?

Validation, auth & security

Input validation (zod, joi, express-validator)

Validate body, params and query at the edge, reject with 400, and pass only parsed, whitelisted data on.

  • Never trust req.body, req.params or req.query. Check types, required fields, formats and ranges before business logic runs.
  • Build a reusable validate(schema) middleware so routes stay clean and errors have one shape.
  • Whitelist: keep only known fields (zod strips unknown keys by default), which blocks mass assignment like isAdmin: true.
  • Coerce strings from params and query (z.coerce.number()), because they never arrive as numbers.
  • Validation (shape) is separate from authorization (may this user do it) and business rules (is the email already taken).
  • Return 400 (or 422) with a list of field errors; never a 500.

Interview questions

  • How do you validate requests in Express?
  • zod vs joi vs express-validator?
  • What is mass assignment and how do you prevent it?

JWT authentication middleware

Verify a signed token from the Authorization header in middleware, put the claims on req.user, then authorize per route.

  • A JWT is header.payload.signature, each part base64url-encoded. The signature proves the token was issued by someone with the key; the payload is readable by anyone.
  • Login flow: check credentials, jwt.sign({ sub, role }, secret, { expiresIn: '15m' }), return the token. Client sends Authorization: Bearer <token>.
  • Middleware: read the header, jwt.verify(token, secret, { algorithms: ['HS256'] }), set req.user, else 401.
  • 401 Unauthorized = not authenticated (no or bad token). 403 Forbidden = authenticated but not allowed.
  • Use short-lived access tokens plus a refresh token (httpOnly cookie, rotated, stored server-side so it can be revoked).
  • Pin the algorithm list and use a strong secret, or RS256/ES256 key pairs when other services must verify tokens.

Interview questions

  • How do you implement JWT authentication in Express?
  • How do you log out or revoke a JWT?
  • Difference between 401 and 403?
  • HS256 vs RS256 for JWTs?

Sessions (express-session) & Passport

Sessions keep auth state on the server keyed by a cookie id; Passport plugs login strategies into that flow.

  • express-session sets a signed cookie holding only a session id; the data lives in a store. Since v1.5 it doesn't need cookie-parser.
  • The default MemoryStore leaks memory and isn't shared between processes. Use Redis (connect-redis) or a DB store in production.
  • Key options: secret, resave: false, saveUninitialized: false, cookie: { httpOnly, secure, sameSite, maxAge }, store, name.
  • Call req.session.regenerate() on login to prevent session fixation, and req.session.destroy() on logout.
  • Passport is auth middleware with 500+ strategies (local, JWT, Google, GitHub OAuth). serializeUser stores the user id in the session; deserializeUser loads the user into req.user on each request.
  • Behind a TLS-terminating proxy, cookie.secure: true needs app.set('trust proxy', 1), otherwise the cookie is never set.

Interview questions

  • How does express-session work?
  • Why shouldn't you use the default MemoryStore in production?
  • Sessions or JWT for a new web app?
  • What do serializeUser and deserializeUser do in Passport?
  • What is session fixation and how do you prevent it?

Security: helmet, CORS, rate limiting & sanitisation

Layer defences: secure headers, a strict CORS allow-list, rate limits, size limits, validated input and parameterised queries.

  • helmet() sets secure headers: Content-Security-Policy, Strict-Transport-Security, X-Content-Type-Options: nosniff, X-Frame-Options, Referrer-Policy, and removes X-Powered-By.
  • cors() controls which browser origins may read responses. Use an allow-list; origin: '*' can't be combined with credentials (browsers reject it).
  • CORS is enforced by browsers only. It is not access control: curl and servers ignore it, so you still need auth.
  • express-rate-limit caps requests per IP/key per window (stricter on /login). Use a Redis store when running many instances.
  • Sanitise/limit input: body limit, validation, parameterised SQL / ORM, reject keys starting with $ for Mongo, escape output in templates to stop XSS.
  • Also: keep dependencies patched (npm audit), store secrets in env/secret managers, use HTTPS everywhere, and use CSRF protection for cookie-based auth.

Interview questions

  • What does helmet do?
  • What is CORS and how do you configure it in Express?
  • Does CORS protect my API from unauthorised clients?
  • How would you rate limit an API running on 10 instances?
  • How do you prevent NoSQL injection in an Express + MongoDB app?

Architecture, logging & testing

Logging: morgan & pino

morgan writes one access-log line per request; pino is a fast structured JSON logger for app and request logs.

  • morgan is HTTP access logging: method, URL, status, response time. Presets: dev (coloured), combined (Apache style), common, short, tiny.
  • pino writes JSON logs with levels and is very fast because it does little work in the main thread. pino-http logs each request and adds req.log.
  • Structured JSON logs are easy to search in ELK, Loki, Datadog or CloudWatch. Use pino-pretty only for local development.
  • Add a request id (from X-Request-Id or generated) to every log line so you can trace one request across services.
  • Never log passwords, tokens or full card numbers; use pino's redact option.
  • Don't use console.log in production code: it has no levels, no structure and is synchronous when writing to a terminal or file.

Interview questions

  • morgan vs pino (or winston)?
  • How would you trace a single request through logs?
  • Why structured (JSON) logs?

Project structure: routes, controllers, services

Keep HTTP code thin: routes wire URLs, controllers translate HTTP, services hold business logic, repositories talk to the DB.

  • Routes: map method + path to middleware and a controller. No logic.
  • Controllers: read validated input from req, call a service, choose status and response shape. Only layer that knows req/res.
  • Services: business rules and transactions, framework-free. Throw domain errors (NotFoundError), never call res.
  • Repositories/models: data access (SQL, Prisma, Mongoose). Swappable and mockable in tests.
  • Split app.js (build and export the app) from server.js (listen, signals). Tests import app without opening a port.
  • Feature folders (src/users/{routes,controller,service,repo}.js) scale better than one folder per layer in large apps. Centralise config in one validated module.

Interview questions

  • How do you structure a large Express application?
  • Why keep req and res out of the service layer?
  • Why separate app.js from server.js?

Testing with supertest

supertest sends real HTTP requests to your exported app on an ephemeral port and asserts status, headers and body.

  • request(app) starts the app on a random free port for the test and closes it after, so you don't call listen().
  • Chain .get()/.post(), .set() headers, .send() a body, then .expect(status), .expect('Content-Type', /json/) or read res.body.
  • Works with Jest, Vitest, Mocha or the built-in node:test runner.
  • Unit tests: services with fake repositories. Integration tests: routes + middleware + a real test DB (Docker/Testcontainers). Mock only external services.
  • Use request.agent(app) to keep cookies across requests (session login flows).
  • Test the unhappy paths: validation 400s, 401/403, 404, and that the error handler hides internals.

Interview questions

  • How do you test an Express API?
  • Why export app instead of the server for tests?
  • What would you mock and what would you keep real in integration tests?

Production & ecosystem

Performance & production: NODE_ENV, compression, cluster, proxies

Run in production mode, behind a reverse proxy, one process per core, with correct trust proxy and graceful shutdown.

  • NODE_ENV=production: Express caches view templates and hides stack traces in error responses; many libraries also skip dev-only work.
  • Never block the event loop: avoid sync APIs (fs.readFileSync, crypto.pbkdf2Sync) and heavy CPU work in handlers. Move CPU work to worker threads or a queue.
  • Compression: compression() middleware gzips responses, but in production it is usually better done by the reverse proxy/CDN (Nginx, ALB, Cloudflare).
  • Use all cores: Node runs JS on one thread. Run several processes with node:cluster, PM2 cluster mode, or more containers/pods behind a load balancer. Keep the app stateless (sessions in Redis).
  • Reverse proxy (Nginx, ALB, Envoy): TLS termination, gzip, static/CDN caching, request size limits, buffering slow clients.
  • app.set('trust proxy', 1) trusts one hop of X-Forwarded-*, so req.ip, req.protocol and req.secure show the client's real values. Set true only if the last proxy overwrites those headers.
  • Graceful shutdown: on SIGTERM, stop accepting (server.close()), finish in-flight requests, close DB pools, then exit. Add /health and /ready endpoints for the orchestrator.

Interview questions

  • What does setting NODE_ENV=production do for Express?
  • Why and how do you use trust proxy?
  • Node is single-threaded. How do you use all CPU cores with Express?
  • Should compression be done in Express or in Nginx?
  • Your Express API's p99 latency spikes under load. How do you investigate?

Express vs Fastify vs NestJS

Express is minimal and universal; Fastify is faster with built-in schemas and plugins; NestJS is a structured TypeScript framework on top of either.

  • Express: tiny core, huge middleware ecosystem, almost every Node developer knows it. You add structure, validation and typing yourself.
  • Fastify: designed for low overhead. JSON Schema validation and serialisation per route, built-in pino logging, an encapsulated plugin system, hooks, and first-class async/await.
  • NestJS: opinionated, TypeScript-first, Angular-style modules, controllers, providers and DI, plus guards, pipes and interceptors. Uses Express by default and can switch to Fastify via an adapter.
  • Express performance is fine for most apps; the database is usually the bottleneck. Fastify wins when per-request overhead matters at high RPS.
  • Express middleware can run in Fastify via @fastify/express or @fastify/middie, which helps gradual migration.

Interview questions

  • Express vs Fastify?
  • Express vs NestJS?
  • Your team is starting a new Node API. Which framework would you pick and why?