Understanding expressjs middleware with a visual example
A middleware function takes 3 arguments as seen below.
function(req, res, next){
// Your business logic goes here
}
Important things to remember about middleware.
- One or more middleware functions comprise the middleware stack.
- Order matters. i.e. Each middleware function is executed in the order in which it was defined in your main application file.
- In a middleware function, invoke the third argument i.e. next() to allow the request to be passed on to the subsequent item in the middleware stack(if there are more middleware functions) or the route handler if this was the last middleware function.
- Middleware functions are most suitable to handle common blanket actions like request logging, authentication etc.
For example, you could implement a simple request logger by defining middleware function that does just that.
function(req, res, next){
// Basic logging for all the routes
console.log(req.method + ':' + req.originalUrl);
next();
};
Express uses middleware to many important things like – manage session, construct the HTTP body etc.
The point about order is perhaps the most important because its the most easily forgotten and can lead you to spend unnecessary time debugging things when you expect them to work. So, just always, always keep that in mind.
That’s all there is to it.