Be the first user to complete this post

  • 0
Add to List

Understanding expressjs middleware with a visual example

An express middleware is nothing but a function that you can specify to be executed between the time when the request reaches the application to when it reaches your route handler. expressjs middleware functions 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.



Also Read:

  1. Send email using nodejs and express in 5 simple steps
  2. Setup passportjs for local authentication and authorization using expressjs
  3. Unit test your Nodejs RESTful API using mocha
  4. What does npm start do in nodejs
  5. Access the request body of a post request in your nodejs - expressjs app.