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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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
- What is middleware in Express? Give examples you have written.
- What is next for? What happens if you forget it?
- In what order do you register JSON parsing, CORS, auth, routes and error handling, and why?
- app.get vs app.use?
- Implement a small middleware runner with next() and error middleware.
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.