🟢 Node.js Intermediate

What is middleware chaining in Express.js?

Why Interviewers Ask This

This question targets practical, hands-on experience with Node.js. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

Answer

Middleware chaining is the sequential execution of multiple middleware functions for a single request, where each function calls next() to pass control to the next function in the chain. The chain runs in the order middleware is registered with app.use() or route methods. Example chain: request logging → authentication → rate limiting → request validation → route handler → error handler. Each middleware can: (1) pass control downstream by calling next(); (2) terminate the chain by sending a response (res.json(), res.send()); (3) short-circuit with an error by calling next(error). Middleware can be applied globally (app.use(fn)), per path (app.use("/api", fn)), or per route (app.get("/", fn1, fn2, handler)). The order of app.use() calls matters — auth middleware must come before protected routes. Reusable middleware is packaged as npm modules (cors, helmet, morgan, express-rate-limit).

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Node.js codebase.