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
- Express is a minimal, unopinionated web framework on top of Node's
httpmodule. An app is just a(req, res)function plus a router and a stack of middleware. - Middleware signature is
(req, res, next). Each one must end the response or callnext(), otherwise the request hangs. - 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.
- An error handler has 4 parameters
(err, req, res, next). Express detects it byfn.length, so you must keep all four even ifnextis unused. next()goes to the next matching layer,next('route')skips the remaining handlers of the current route,next('router')leaves the router, andnext(err)jumps to error handlers.- 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. req.params= path segments (/users/:id),req.query= query string,req.body= parsed body (needsexpress.json()orexpress.urlencoded()). All values arrive as strings (except a JSON body).express.Router()is a mini-app with its own middleware and routes. Mount it withapp.use('/api/users', router). UsemergeParams: trueto see parent params.- 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. - Express 5 removed
app.del,req.param(),res.send(status),res.json(obj, status),res.sendfileandres.redirect('back'). It needs Node 18+. - Validate every input at the edge (zod, joi or express-validator) and pass only the validated, whitelisted data on to services.
- 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.
- Security baseline:
helmet(), a strictcors()allow-list,express-rate-limit, body size limits,app.disable('x-powered-by')(helmet already removes it), and parameterised DB queries. - Production:
NODE_ENV=production, a structured logger (pino), a reverse proxy for TLS/gzip,app.set('trust proxy', 1)soreq.ipandreq.secureare correct, and one process per core (cluster/PM2/containers). - Test with supertest: export the
appwithout callinglisten(), thenrequest(app).get('/users').expect(200). - 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()andreq.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 justhttp.createServer(app).listen(port), so you can also passappto anhttpsserver.- 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/:idputs the segment inreq.params.id. Values are always strings, so convert and validate them. - Query string:
/search?q=js&page=2givesreq.query.qandreq.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.queryandreq.body? - What is route chaining with
app.route()? - Why does
GET /users/mereturn "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 nolisten()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 readreq.paramsof the parent. - Inside a mounted router,
req.baseUrlis the mount path,req.pathis the rest, andreq.originalUrlis the full original URL.
Interview questions
- What is
express.Routerand why use it? - Difference between
appand aRouter? - What does
mergeParamsdo?
Request & response objects
req and res are Node's objects extended with helpers; send exactly one response per request.
- Useful
reqfields:params,query,body,headers,get(name),method,path,originalUrl,ip,hostname,protocol,secure,cookies(with cookie-parser). - Useful
resmethods:status(),json(),send(),sendStatus(),set(),cookie(),clearCookie(),redirect(),sendFile(),download(),render(),end(). res.status()andres.set()returnres, so you can chain:res.status(201).json(user).res.json()serialises withJSON.stringifyand setsContent-Type: application/json.res.send()guesses the type from its argument.res.localsholds data for the current request only (e.g. the logged-in user for views).app.localslives for the whole app.- Send one response. A second
res.json()throwsERR_HTTP_HEADERS_SENT. Checkres.headersSentwhen unsure.
Interview questions
- Difference between
res.send(),res.json()andres.end()? - What causes "Cannot set headers after they are sent to the client"?
- Difference between
res.localsandapp.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. setreq.user), end the cycle by responding, or callnext(). - 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
throwinside middleware is caught by Express and treated likenext(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
appwithapp.use()orapp.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()andexpress.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')andnext(err)? - Difference between
app.use('/api', fn)andapp.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 whoseContent-Typeis JSON. Other types are skipped, soreq.bodystaysundefinedin Express 5 (it was{}in Express 4).express.urlencoded()parses HTML form posts. In Express 5extendeddefaults to false (simplequerystring); setextended: truefor nested objects viaqs.- Both have a
limitoption (default 100kb). Bodies above it get 413 Payload Too Large; invalid JSON gives 400. - File uploads (
multipart/form-data) are not handled by Express; usemulterorbusboy. express.static('public', opts)serves files with correct type, ETag andCache-Control(maxAge). It callsnext()if the file isn't found.- Express 5 static:
dotfilesdefaults to'ignore', which also hides dot-directories like.well-knownunless you allow them.
Interview questions
- Why is
req.bodyundefined in my POST route? - Difference between
express.json()andexpress.urlencoded()? - How do you handle file uploads in Express?
- How does
express.staticwork 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 syncthrow, 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.headersSentis true (e.g. a stream failed halfway), callnext(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.headersSentin 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
throwis 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 likeasyncHandler(fn), or theexpress-async-errorspatch 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-stylefs.readFile(cb), event emitters). Pass those tonext(err)yourself. - Errors raised in a stream's
'error'event must also be forwarded manually, or usestream.pipelinewith a callback that callsnext.
Interview questions
- What happens when an async route handler throws in Express 4?
- How did Express 5 change async error handling?
- Write an
asyncHandlerwrapper 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 expressnow 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.paramshas a null prototype for string paths, wildcard values are arrays of segments, and unmatched optional params are omitted.req.queryis now a getter (not writable) and uses the simple parser by default;req.bodyisundefinedwhen not parsed;urlencodedextendeddefaults tofalse.res.status()only accepts integers 100–999;app.listenpasses server errors (likeEADDRINUSE) 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.paramsa 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.paramsorreq.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 (
zodstrips unknown keys by default), which blocks mass assignment likeisAdmin: 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 sendsAuthorization: Bearer <token>. - Middleware: read the header,
jwt.verify(token, secret, { algorithms: ['HS256'] }), setreq.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-sessionsets a signed cookie holding only a session id; the data lives in a store. Since v1.5 it doesn't needcookie-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, andreq.session.destroy()on logout. - Passport is auth middleware with 500+ strategies (local, JWT, Google, GitHub OAuth).
serializeUserstores the user id in the session;deserializeUserloads the user intoreq.useron each request. - Behind a TLS-terminating proxy,
cookie.secure: trueneedsapp.set('trust proxy', 1), otherwise the cookie is never set.
Interview questions
- How does
express-sessionwork? - Why shouldn't you use the default MemoryStore in production?
- Sessions or JWT for a new web app?
- What do
serializeUseranddeserializeUserdo 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 removesX-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-httplogs each request and addsreq.log. - Structured JSON logs are easy to search in ELK, Loki, Datadog or CloudWatch. Use
pino-prettyonly for local development. - Add a request id (from
X-Request-Idor generated) to every log line so you can trace one request across services. - Never log passwords, tokens or full card numbers; use pino's
redactoption. - Don't use
console.login 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 knowsreq/res. - Services: business rules and transactions, framework-free. Throw domain errors (
NotFoundError), never callres. - Repositories/models: data access (SQL, Prisma, Mongoose). Swappable and mockable in tests.
- Split
app.js(build and export the app) fromserver.js(listen, signals). Tests importappwithout 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
reqandresout of the service layer? - Why separate
app.jsfromserver.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 calllisten().- Chain
.get()/.post(),.set()headers,.send()a body, then.expect(status),.expect('Content-Type', /json/)or readres.body. - Works with Jest, Vitest, Mocha or the built-in
node:testrunner. - 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
appinstead 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 ofX-Forwarded-*, soreq.ip,req.protocolandreq.secureshow the client's real values. Settrueonly 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/healthand/readyendpoints for the orchestrator.
Interview questions
- What does setting
NODE_ENV=productiondo 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/expressor@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?