Middleware In ExpressJS

What's missing in NodeJS?

NodeJS is used for writing JavaScript which executes at the server. At the client side, the browser is responsible for handling the JavaScript. So, whenever we use pure NodeJS for creating backend applications our app contains a single function for each incoming request which is responsible for doing all the processing based on the request received and provides the data which will be sent back to the client. We use response.end() to signal to node that the response is done and can be sent back to the client.

This method of development is fine if the processing to be done inside the function is relatively small, but if the code size increases then it is not advisable to use NodeJS for this. The solution to this problem is provided by ExpressJS (a NodeJS framework) in the form of middleware functions. Middleware in ExpressJS is an array of functions which is also called middleware stack. The execution will start from the first function inside the middleware stack and will go to the next function in the array and so on.

So in this case what happens is rather than NodeJS handling the request, it passes it to the ExpressJS app which uses the middleware functions from the stack for various operations.

Each function in the middleware stack has three arguments, the first two are the req (request) and res (response) objects, and the third argument is a function called 'next'. 'next' holds the reference to the next function in the middleware stack and upon calling 'next' the next function in the stack is called.

The most important thing to follow in this whole process is that from all the functions in the middleware stack, one of the function must call res.send which will end the request and send the response back. res.send must only be called once inside our whole stack or else it will throw an error.

Let us see an example to better understand the middleware concept.

  1. <pre name="code" class="javascript">  
  2.     var express=require('express');  
  3.   
  4.     //creates an express application and puts it inside app variable  
  5.     var app=express();  
  6.   
  7.     // first middleware function to log the details onto the console  
  8.     app.use(function(req, res, next){  
  9.         console.log('req IP : '+req.url);  
  10.         console.log('req date : '+new Date());  
  11.         next();  
  12.     });  
  13.   
  14.     // second function to do some processing and send the result back to the client  
  15.     app.use(function(req,res, next){  
  16.         res.end('Data being send from second middleware function');  
  17.     });  
  18.   
  19.     app.listen(3000,function(){  
  20.         console.log('app started on port 3000!');  
  21.     });  
  22. </pre>  

 


Similar Articles