Understanding middleware function in node

Posted By : Abhimanyu Singh | 30-Mar-2015

In this blog , we will see how middleware plays a huge role in our Node and Express application . I just love middleware function . It makes things easy for all node developers.

 

Authorization , Authentication ,Cors , logging everything can be implemented as middleware.

 

Node.js middleware function : A middleware is simply a javascript function that accepts three arguments : a request object , a response object and a callback function commonly name next . Next is callback function indicating that the middleware is done nad the next middleware can be executed.

 

Middleware is a function that returns other function. this is a powerful Javascript feature called a "closure".

 

function myHelloMiddleWare(){
	var options = "hello";
	return function(req,res,next){
 	console.log(options); // replace it with your logic
 	next(); // call the next function
	}
}

Now this function can be called in our node application

app.use(myHelloMiddleWare());

Middleware ordering matter the most . app.use() run the middleware function in the order it is defined the in the application.

for example:


  var bodyParser = require('bodyParser');
  function printRequestBody(){
    return function(req,res,next){
       console.log(req.body);
       next();
    }
  }
  app.use(bodyParser());
  app.use(printRequestBody())

This bodyParser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings. A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body).

If we reverse the order like

 

  app.use(printRequestBody());
  app.use(bodyParser());

Now printRequestBody() parser will print null rather than req.body since it is not available as bodyParser will run after the printRequestBody().

 

I hope , it will help you to understand middleware in node.

 

Thanks

Abhimanyu

 

 

About Author

Author Image
Abhimanyu Singh

Abhimanyu is an seasoned technologist . He always keeps himself ahead in embracing and adapting new technologies/frameworks to solve business problems. He specialise in Blockchain technology , Video Content Management & enterprise software .

Request for Proposal

Name is required

Comment is required

Sending message..