Understanding Middleware in ExpressJS

Thing missing in NodeJS
NodeJS is used for writing JavaScript which executes at the server. At client side browser is responsible for handling the JavaScript. So, whenever we use pure NodeJS for creating backend applications our app contain 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 send back to the client. We use response.end() to signal node that response is done and can be send 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 passed that to the ExpressJS app which uses the middleware functions from the stack for various operations.

Each function in the middleware stack has got three arguments, the first two are the req(request) and res(response) objects and 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 else it will throw an error.

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

var express=require('express');

//creates an express application and puts it inside app variable
var app=express();

// first middleware function to log the details onto the console
app.use(function(req, res, next){
    console.log('req IP : '+req.url);
    console.log('req date : '+new Date());

// second function to do some processing and send the result back to the client
app.use(function(req,res, next){
    res.end('Data being send from second middleware function');

   console.log('app started on port 3000!');

Related Posts