What is middleware in Express.js?

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.