Middleware is software glue
blog image source |
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. These functions are used to modify req and res objects for tasks like parsing request bodies, adding response headers, etc.
- functions that have access to the request and response
- gets called before the controller function
- can modify the request object that gets passed to the controller
- can send a response and prevent the controller being accessed
- used for common tasks that are not the responsibility of any single
- controller:
- authentication
- request Body Validation
- logging
- redirection
- error handling
- can be applied at application or route level
- application level applies to all requests
- route level applies to certain routes
- express comes with a few builds in middleware functions
- express.json - parses JSON requests
- express.static - serves static files
- can also install others from npm, or write your own
Middleware: THE core of node.js backend apps - https://hackernoon.com/middleware-the-core-of-node-js-apps-ab01fee39200
Express.js Middleware Demystified - https://www.safaribooksonline.com/blog/2014/03/10/express-js-middleware-demystified/
Using middleware - https://expressjs.com/en/guide/using-middleware.html