What is middleware chaining in Express.js?
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).