Skip to the page

Express basics · core

Middleware and next()

Middleware is a function (req, res, next) that runs in the order it was added; each one either ends the response or calls next() to pass control on, which is how Express builds parsing, logging, auth and error handling as a pipeline.

The notes

What you must know

  • A middleware can run code, change req/res (e.g. set req.user), end the request (res.send/json), or call next() to continue. If it does neither, the request hangs.
  • Order is registration order: the body parser before routes that read req.body, auth before protected routes, error handlers last.
  • Scopes: app-level (app.use(fn)), path-level (app.use('/admin', fn)), router-level, and route-level (app.get('/x', auth, handler)).
  • next() continues; next(err) jumps to error-handling middleware; next('route') skips the remaining handlers of the current route.
  • Common bug: forgetting return after res.status(...).json(...), so code keeps running and later calls next() or sends again.
  • Popular middleware: express.json, cors, helmet, express-rate-limit, pino-http, compression, cookie-parser, express-session.
  • Same idea elsewhere: Koa's async 'onion' compose, Next.js proxy.ts, Redux middleware.

The red pen

Common traps: mistake → fix

  • Mistake: Middleware runs in parallel

    Fix: it runs one after another, in registration order.

  • Mistake: Forgetting next() is harmless

    Fix: the request hangs until a timeout.

  • Mistake: res.json() stops the function

    Fix: it sends the response, but your code keeps running; add return.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is middleware in Express? Give examples you have written.
  2. What is next for? What happens if you forget it?
  3. In what order do you register JSON parsing, CORS, auth, routes and error handling, and why?
  4. app.get vs app.use?
  5. Implement a small middleware runner with next() and error middleware.

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview