What is middleware in Express.js?
Why Interviewers Ask This
Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid Node.js basics — a prerequisite for any developer role.
Answer
Middleware in Express.js is a function that has access to the request object (req), response object (res), and the next function in the request-response cycle. Middleware functions can: execute code, modify req/res objects, end the request-response cycle, or call next() to pass control to the next middleware. Types of Express middleware: (1) Application-level: bound to app.use() or app.METHOD(); (2) Router-level: bound to an express.Router() instance; (3) Error-handling: has 4 parameters (err, req, res, next); (4) Built-in: express.json(), express.urlencoded(), express.static(); (5) Third-party: cors, morgan, helmet, passport. Middleware executes in the order it is defined. If a middleware does not end the cycle or call next(), the request will hang.
Common Mistake
Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong Node.js candidates.