Skip to content

Interview PrepExpress · Core

Middleware ​

15. What is middleware in Express, and why is it useful? ​

The short answer

Middleware is a function that receives the request, the response and a next function, and sits in a pipeline that every request passes through in order. Each one can read or change the request and response, end the request by sending a response, or call next() to hand over to the next function. It lets you write cross-cutting steps once, such as logging, parsing bodies, authentication, rate limiting and error handling, and apply them to every route or to a group, instead of repeating them inside each handler.

request① loggernext()② json()next()③ authnext() or 401④ handlerres.json()401, stop hereerror handlernext(err)
A conveyor belt of small steps. Each middleware does one job and passes the request along with next(). Any step can stop the request by responding, and any error skips ahead to the error handler.
ts
function requestLogger(req: Request, res: Response, next: NextFunction) {
  const start = Date.now()
  res.on('finish', () => {                                                    // (1)
    logger.info({ method: req.method, path: req.originalUrl, status: res.statusCode, ms: Date.now() - start })
  })
  next()                                                                      // (2)
}

app.use(requestLogger)
app.use(express.json())
app.use('/api/orders', requireUser, ordersRouter)
  1. Run code after the response is sent, by listening for the response's finish event.
  2. Pass control on. Without next() or a response, the request hangs until the client times out.

Why middleware is useful: each concern is written once, tested on its own, and applied consistently. Adding rate limiting to every route is one app.use line, not a change to fifty handlers.

16. What does next() do in Express middleware? ​

The short answer

next() tells Express this middleware is finished and the request should move to the next matching middleware or route handler. Calling next(err) with an error skips every normal middleware and jumps to the error-handling middleware. Calling next('route') skips the remaining handlers of the current route and moves to the next matching route. If a middleware neither calls next nor sends a response, the request hangs.

CallEffect
next()Continue to the next matching function
next(err)Skip to error-handling middleware (question 32)
next('route')Skip the rest of this route's handlers
next('router')Leave the current router entirely
Neither, and no responseThe request hangs
ts
function requireUser(req: Request, res: Response, next: NextFunction) {
  if (!req.session?.userId) {
    return res.status(401).json({ error: 'sign_in_required' })        // (1) stop here
  }
  next()                                                               // (2) continue
}

async function loadOrder(req: Request, res: Response, next: NextFunction) {
  const order = await orders.find(req.params.id)
  if (!order) return next(new NotFoundError('order'))                  // (3) to the error handler
  res.locals.order = order
  next()
}
  1. Responding ends the request, so do not call next too. return makes sure the rest of the function does not run.
  2. Everything is fine: carry on.
  3. An error: hand it to the central error handler (question 35).

A common bug: calling next() and then also sending a response, which produces "Cannot set headers after they are sent".

17. How does middleware execution order work? ​

The short answer

Express runs middleware and routes in exactly the order they were registered, from top to bottom, skipping any whose path or method does not match the request. Each must call next() for the request to reach the following one. That order is your design: body parsers must come before routes that read the body, authentication before protected routes, the 404 handler after all routes, and error handlers last of all.

ts
app.use(helmet())                          // 1. security headers on every response
app.use(requestLogger)                     // 2. log everything, even rejected requests
app.use(express.json({ limit: '100kb' }))  // 3. parse bodies before anything reads them
app.use(rateLimiter)                       // 4. reject floods early, before expensive work

app.get('/health', health)                 // 5. public, before authentication
app.use('/api', authenticate)              // 6. everything under /api needs a user
app.use('/api/orders', ordersRouter)       // 7. routes

app.use(notFound)                          // 8. nothing matched
app.use(errorHandler)                      // 9. always last

Mistakes that come from order:

MistakeSymptom
Routes before express.json()req.body is undefined
Authentication after the routes it should protectRoutes are public
Error handler registered before routesIt never receives their errors
CORS middleware after a router that respondsPreflight requests fail
Logger after a middleware that rejects requestsRejected requests are never logged

Code after next() runs too: Express is not a strict "onion" like Koa, but a middleware can do work after the rest of the chain by listening for res.on('finish') (question 15).

18. What are the different types of Express middleware? ​

The short answer

Express documentation names five kinds. Application-level middleware is attached to the app with app.use or app.METHOD. Router-level middleware is attached to an express.Router(). Error-handling middleware takes four arguments, (err, req, res, next), and only runs when an error is passed on. Built-in middleware ships with Express: express.json, express.urlencoded and express.static. Third-party middleware comes from npm, such as helmet, cors and cookie-parser.

KindRegistered withExample
Application-levelapp.use, app.getapp.use(requestLogger)
Router-levelrouter.use, router.getordersRouter.use(requireUser)
Error-handlingFour parametersapp.use((err, req, res, next) => …)
Built-inShips with Expressexpress.json()
Third-partynpm packageshelmet(), cors(), compression()

You will also hear route-level middleware: functions passed to a single route, such as app.post('/orders', validateBody, createOrder) (question 21).

19. What is the difference between application-level and router-level middleware? ​

The short answer

Application-level middleware is added to the main app, and runs for every request, or every request under a given path, across the whole application. Router-level middleware is added to a specific router, and runs only for requests that reach that router. Use application-level for concerns that apply everywhere, such as security headers and logging, and router-level for concerns that belong to one area, such as "every admin route needs an admin".

ts
app.use(helmet())                               // application-level: every request
app.use(requestLogger)

const adminRouter = Router()
adminRouter.use(requireRole('admin'))           // router-level: only /admin routes
adminRouter.get('/refunds', listRefunds)
app.use('/admin', adminRouter)

const publicRouter = Router()
publicRouter.get('/products', listProducts)     // no admin check here
app.use('/', publicRouter)

Why router-level is safer for access control: a new route added to adminRouter is protected automatically. With a check inside each handler, one forgotten line exposes an admin endpoint.

20. What is the difference between built-in, third-party, and custom middleware? ​

The short answer

Built-in middleware ships with Express itself: express.json(), express.urlencoded(), express.static(), express.raw() and express.text(). Third-party middleware is installed from npm and maintained by others, such as helmet for security headers, cors, cookie-parser, compression and express-rate-limit. Custom middleware is what you write for your own needs, such as authentication against your session store, tenant resolution or request IDs. They all have the same shape and work the same way.

KindExamplesChoose it when
Built-inexpress.json, express.staticAlways available, no extra dependency
Third-partyhelmet, cors, compression, express-rate-limit, pino-httpA common, well-tested solution exists
CustomrequireUser, resolveTenant, requestIdLogic specific to your application

Choosing third-party middleware is choosing a dependency. Check that it is maintained, widely used and does one thing; it runs on every request with full access to the request and response.

21. What is route middleware? ​

The short answer

Route middleware is middleware attached to a single route, by passing it as an extra argument before the handler, such as app.post('/orders', requireUser, validate(OrderInput), createOrder). It runs only for that method and path, in the order listed. It is how you apply checks that only some routes need, such as a specific permission, body validation, a rate limit for one sensitive endpoint, or loading a resource.

ts
app.post(
  '/orders/:id/refund',
  requireUser,                                  // (1)
  requireRole('support'),                       // (2)
  validate(RefundInput),                        // (3)
  rateLimit({ windowMs: 60_000, limit: 10 }),   // (4)
  async (req, res) => {
    const refund = await refunds.create(req.params.id, req.body)
    res.status(201).json(refund)
  },
)
  1. Who are you?
  2. Are you allowed to refund?
  3. Is the request well formed? (question 66)
  4. A stricter limit for this sensitive action only.

Reading the route now tells you everything that happens before the handler runs.

22. What is the difference between middleware and a route handler? ​

The short answer

Technically, both are functions with (req, res, next). The difference is their job. Middleware does something along the way and normally calls next(), such as parsing, logging, checking authentication or adding data. A route handler is the final function for a specific method and path: it does the actual work for that endpoint and sends the response, without calling next() unless something fails.

MiddlewareRoute handler
JobA step for many requestsThe endpoint's real work
Usually callsnext()res.json(), res.status().send()
Registered withapp.use, or before a handlerapp.get, app.post and so on
ExamplerequireUsercreateOrder

A function can be both: a middleware that answers some requests, such as returning a cached response, and passes others on.

23. How do you write custom middleware? ​

The short answer

Write a function (req, res, next) that does one job and then either calls next(), ends the request with a response, or calls next(err). When it needs options, write a factory: a function that takes the options and returns the middleware, such as requireRole('admin'). Attach data for later steps to res.locals or a typed property on req. Keep each middleware small, so it can be reused and understood alone.

A request ID middleware:

ts
import { randomUUID } from 'node:crypto'
import type { Request, Response, NextFunction } from 'express'

export function requestId(req: Request, res: Response, next: NextFunction) {
  const id = req.get('x-request-id') ?? randomUUID()      // (1)
  res.locals.requestId = id                               // (2)
  res.set('x-request-id', id)                             // (3)
  next()
}
  1. Reuse the caller's ID if a gateway already set one, so logs across services match.
  2. Make it available to later middleware and handlers.
  3. Return it to the client, so a user can quote it to support.

A configurable middleware, with a factory:

ts
export function requireRole(...roles: Role[]) {
  return (req: Request, res: Response, next: NextFunction) => {        // (1)
    if (!req.user) return res.status(401).json({ error: 'sign_in_required' })
    if (!roles.includes(req.user.role)) return res.status(403).json({ error: 'forbidden' })   // (2)
    next()
  }
}

app.delete('/products/:sku', requireRole('admin'), deleteProduct)
  1. The factory returns the real middleware, which closes over roles (the closures question).
  2. 401 means "who are you?", 403 means "you are not allowed" (question 44).

Typing req.user across the app is done once with declaration merging, shown in the type versus interface question.

24. How do you write asynchronous middleware? ​

The short answer

Write it as an async function and await the asynchronous work, such as a session lookup. In Express 5, if the promise rejects, Express catches it and passes the error to your error handler automatically. In Express 4, it did not, so a rejected promise was never handled and the request hung; you had to wrap the body in try/catch and call next(err), or use a wrapper. Either way, make sure the middleware ends by calling next() or sending a response.

ts
// Express 5: a rejection is forwarded to the error handler for you
export async function loadSession(req: Request, res: Response, next: NextFunction) {
  const token = req.cookies.session
  if (!token) return next()
  const session = await sessions.find(token)                    // (1) if this throws, Express catches it
  if (session && session.expiresAt > new Date()) req.user = session.user
  next()
}

// Express 4: you must catch it yourself
export function loadSessionV4(req: Request, res: Response, next: NextFunction) {
  sessions.find(req.cookies.session)
    .then((session) => { req.user = session?.user; next() })
    .catch(next)                                                  // (2)
}
  1. In Express 5, a thrown error or rejected promise becomes next(err) automatically (question 33).
  2. In Express 4, forward errors explicitly, or the request hangs and the rejection may crash the process.

One trap remains in Express 5: errors in callbacks or timers that are not part of the returned promise, such as inside setTimeout or an old callback API, are still not caught. Wrap such APIs in promises and await them.

25. How would you implement logging, authentication, and authorization middleware? ​

The short answer

Logging middleware records each request's method, path, status, duration and a request ID, written as structured JSON when the response finishes. Authentication middleware reads the credential, a session cookie or a bearer token, verifies it, and attaches the user to the request, or responds 401. Authorisation middleware checks whether that user may perform the action, by role or by ownership of the resource, and responds 403 if not. Chain them in that order, and keep the final ownership checks close to the data.

ts
import pinoHttp from 'pino-http'
import { jwtVerify, createRemoteJWKSet } from 'jose'

// 1. Logging: one structured line per request
app.use(pinoHttp({ genReqId: (req) => req.headers['x-request-id'] ?? randomUUID() }))   // (1)

// 2. Authentication: who is calling?
const jwks = createRemoteJWKSet(new URL('https://login.shop.example/.well-known/jwks.json'))
export async function authenticate(req: Request, res: Response, next: NextFunction) {
  const header = req.get('authorization') ?? ''
  const token = header.startsWith('Bearer ') ? header.slice(7) : null
  if (!token) return res.status(401).json({ error: 'missing_token' })
  try {
    const { payload } = await jwtVerify(token, jwks, {                                   // (2)
      issuer: 'https://login.shop.example', audience: 'shop-api',
    })
    req.user = { id: payload.sub!, role: payload.role as Role }
    next()
  } catch {
    res.status(401).json({ error: 'invalid_token' })
  }
}

// 3. Authorisation: may they do this?
export function canAccessOrder() {
  return async (req: Request, res: Response, next: NextFunction) => {
    const order = await orders.find(req.params.id)
    if (!order) return res.status(404).json({ error: 'not_found' })
    if (order.customerId !== req.user!.id && req.user!.role !== 'support') {           // (3)
      return res.status(404).json({ error: 'not_found' })                                // (4)
    }
    res.locals.order = order
    next()
  }
}

app.get('/api/orders/:id', authenticate, canAccessOrder(), (req, res) => res.json(res.locals.order))
  1. Structured request logs with a request ID, using Pino (question 41).
  2. Verify the token's signature, issuer, audience and expiry, never just decode it. Tokens and their checks are covered in depth in how a JWT is signed and verified.
  3. Ownership check: a customer may only see their own orders.
  4. Answering 404 instead of 403 avoids telling an attacker that order 42 exists.

The bug this prevents most often is broken object-level authorisation: changing /orders/41 to /orders/42 in the URL and seeing someone else's order. Every route that takes an ID must check the user's right to that specific record.

26. What is router.param(), and when is it useful? ​

The short answer

router.param(name, fn) registers a function that runs whenever a route on that router contains the parameter name, before the route's handlers, and receives the parameter's value. It is useful for loading or validating a resource once for every route that uses it, such as turning :orderId into an order object, or returning 404 if it does not exist, instead of repeating the same lookup in each handler.

ts
ordersRouter.param('orderId', async (req, res, next, orderId: string) => {
  if (!/^ord_[a-z0-9]{12}$/.test(orderId)) return res.status(400).json({ error: 'bad_order_id' })   // (1)
  const order = await orders.find(orderId)
  if (!order) return res.status(404).json({ error: 'not_found' })
  res.locals.order = order                                                                         // (2)
  next()
})

ordersRouter.get('/:orderId', (req, res) => res.json(res.locals.order))
ordersRouter.post('/:orderId/cancel', cancelOrder)          // the order is already loaded
  1. Validate the format before touching the database.
  2. Load once, for every route on this router that has :orderId.

Remember authorisation. Loading the order is not the same as checking the user may see it; that check still belongs here or in the route (question 25).

27. What are app.locals and res.locals? ​

The short answer

app.locals is an object that lives for the whole application, shared by every request, used for values such as the site name or configuration available to templates. res.locals is an object that exists for one request only, used to pass data from one middleware to the next or to the view, such as the loaded user, a request ID or a resource fetched by an earlier middleware. Never put per-user data in app.locals, because every user would see it.

app.localsres.locals
LifetimeThe whole applicationOne request
Shared between usersYesNo
Typical contentsSite name, build version, static configurationCurrent user, request ID, loaded resource
Available in templatesYesYes
ts
app.locals.appName = 'Corner Shop'

app.use((req, res, next) => {
  res.locals.requestId = randomUUID()           // only this request
  next()
})

A dangerous mistake: app.locals.currentUser = user inside a middleware. Requests from different users run interleaved, so one user's page can show another user's name.

28. What is trust proxy in Express, and when should it be enabled? ​

The short answer

When your app runs behind a load balancer or reverse proxy, every request appears to come from the proxy, and over plain HTTP from it. The proxy passes the real client's IP and protocol in X-Forwarded-For and X-Forwarded-Proto headers. The trust proxy setting tells Express to believe those headers, so req.ip, req.protocol and req.secure show the real client values. Enable it only for the proxies you actually have, such as app.set('trust proxy', 1) for one hop, because otherwise clients can fake their IP.

ts
app.set('trust proxy', 1)         // exactly one proxy in front: the load balancer

What it changes:

PropertyWithout trust proxyWith it
req.ipThe load balancer's IPThe client's IP
req.protocolhttp, between proxy and apphttps, what the client used
req.securefalsetrue
secure: true cookiesNot sent, because Express thinks it is HTTPWork

Why the value matters, not just on or off:

SettingMeaning
false, the defaultIgnore forwarded headers
1Trust one hop: take the address added by the nearest proxy
'loopback, 10.0.0.0/8'Trust proxies on those addresses
trueTrust everything: a client can send its own X-Forwarded-For and choose its IP

Where a wrong setting hurts: a rate limiter keyed on req.ip either limits everyone together, because all requests share the load balancer's IP, or can be bypassed, because attackers invent an IP in the header. The risks of forwarded headers are covered in the security module.

29. How should an Express application be structured for production? ​

The short answer

Separate the HTTP layer from the business logic. Group code by feature, such as orders and products, each with a router that only handles HTTP concerns, a service with the business rules, and a repository that talks to the database. Keep configuration validated in one module, register global middleware in a clear order, finish with a 404 handler and a central error handler, and keep server start-up, and graceful shutdown, separate from building the app, so the app can be imported without listening on a port.

text
src/
  app.ts                  builds the Express app: middleware, routers, error handler
  server.ts               starts listening, handles SIGTERM
  config.ts               validated environment variables
  middleware/
    authenticate.ts
    error-handler.ts
    request-id.ts
  modules/
    orders/
      orders.router.ts    HTTP: parse, validate, call the service, respond
      orders.service.ts   business rules: pricing, stock, state changes
      orders.repo.ts      database queries
      orders.schema.ts    Zod schemas for input and output
    products/
      ...
  lib/
    db.ts
    logger.ts
ts
// app.ts
export function buildApp(deps: { db: Db; logger: Logger }) {      // (1)
  const app = express()
  app.set('trust proxy', 1)
  app.use(helmet(), requestId, pinoHttp({ logger: deps.logger }), express.json({ limit: '100kb' }))
  app.get('/health', (_req, res) => res.send('ok'))
  app.use('/api/orders', authenticate, ordersRouter(deps))
  app.use(notFound)
  app.use(errorHandler(deps.logger))
  return app
}

// server.ts
const app = buildApp({ db, logger })
const server = app.listen(config.PORT)                             // (2)
process.once('SIGTERM', () => shutdown(server))
  1. The app is built by a function that receives its dependencies, so it can be started with real ones in production and different ones elsewhere.
  2. Listening happens only in server.ts.

Rules that keep it maintainable:

RuleWhy
Routers do not contain business logicThe same rule can be used from a queue worker or a script
Services do not touch req and resThey stay independent of Express
One error format, set in one placeClients get consistent errors (question 61)
No process.env outside config.tsConfiguration is checked once, at start-up

30. How do you use express.Router() effectively in a large application? ​

The short answer

Give each feature its own router file, exported from a factory function that receives its dependencies, and mount them all in one place in app.ts, so the whole URL structure is visible at a glance. Attach middleware at the right level: global concerns on the app, area-wide concerns such as authentication or admin checks on the router, and route-specific checks on single routes. Use mergeParams for nested resources, and keep version prefixes such as /v1 at the mount point, not inside every route.

ts
// modules/orders/orders.router.ts
export function ordersRouter({ orders }: { orders: OrdersService }) {
  const r = Router()
  r.get('/', async (req, res) => res.json(await orders.list(req.user!.id, ListQuery.parse(req.query))))
  r.post('/', validate(CreateOrder), async (req, res) => res.status(201).json(await orders.create(req.user!.id, req.body)))
  r.use('/:orderId/items', itemsRouter({ orders }))             // nested, with mergeParams inside
  return r
}

// app.ts: the whole API surface in one place
const v1 = Router()
v1.use('/products', productsRouter(deps))                       // public
v1.use('/orders', authenticate, ordersRouter(deps))             // signed-in users
v1.use('/admin', authenticate, requireRole('admin'), adminRouter(deps))
app.use('/api/v1', v1)

Signs a router structure needs work: the same check copied into many handlers, a router file over a few hundred lines, routes mounted in several different files, or authentication applied per route instead of per area, where one forgotten route becomes public.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Express & REST APIs
Express
REST API design
Testing
Other topics
Nothing picked yet