Skip to the page

Node.js frameworks · Concept

Express middleware and the order it runs in

The interviewer asks

What is middleware in Express? Walk me through what happens to a request from app.use to the response, and where error-handling middleware fits.

Then

Follow-ups the interviewer asks next

  1. What happens if a middleware neither calls next() nor sends a response?
  2. How does Express know a middleware handles errors?
  3. Does order matter? Give an example where it breaks.
  4. Router-level vs app-level middleware?
  5. How would you write a middleware that logs how long each request took?

The answer

What a strong answer covers

  • Middleware are (req, res, next) functions in a stack, run in the order they were registered, for matching paths. Each one either ends the response or calls next().
  • next(err) skips to error handlers, which take four arguments (err, req, res, next) and are registered after the routes.
  • A middleware that never calls next() or responds leaves the request hanging until a timeout.
  • Order bugs: a route registered before the body parser sees no body (in Express 5 req.body is undefined when no parser ran); auth added after the routes protects nothing; a catch-all route placed first swallows the rest.
  • express.Router() scopes middleware to a path prefix.
  • Timing: note process.hrtime.bigint() at the start and log on res.on('finish').

The red pen

Common traps

Avoid:an error handler with three arguments; thinking code after next() runs after the response; calling next() after sending.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

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

Start your free interview