Middleware functions in Express.js are used to provide extra functionality to the framework. Middleware has access to the request (req) and response (res) objects, which it uses to execute commands during the request-response cycle. Overall, it can serve the following purposes:
next() commandreq and res objectsDevelopers can either build their own middleware functions or utilize third-party tools fo the same tasks. A list of third-party middleware is available here.
{
"name": "node-express-middleware",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "PORT=3000 node index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^2.3.4",
"express": "^4.13.3"
}
}The example given above shows the application level, router level, and error handling middleware. The key difference between application-level middleware and router-level middleware is that the former is bound to an application object and the latter is bound to a router object. If a fourth argument is passed to the function, it is automatically considered an error-handling middleware.
The next() function is used to invoke the next appropriate middleware function. If this function is not called and the request-response cycle is not ended, then the request will be left hanging.
Free Resources