Getting Started With Express 4.x – Middleware – Tutorial 5

In this blog post we will see what is express middleware and how to use it

Middleware are modules or pieces of code which execute on every app request, depending on the path specified.
Middleware are a chain of functions, which work sequentially one after the other. The order depends in priority in which they are defined in code.
Lets take an example to get a better understanding

app.use(function(req,res,next){
   console.log('Request Recieved On ' + new Date());
   next();
});

This is simple middleware, which simply logs all requests.
“next();” is an important function which calls the next middleware in chain. If next() is not called execution will stop and even routes will not get called.

Another use of middleware could be to authenticate all requests

app.use(function(req,res,next){
    var api_key = req.api_key;
    var api_secret = req.api_secret;
    authenticate(api_key,api_secret,function(err){
       if(err){
          res.sendStatus(403);
       }else{
          next();
       }
   });
});

next() supports async operations as can be seen above.

There are many 3rd party middleware modules available, which add features to your application. These can be seen here http://expressjs.com/resources/middleware.html

More use options of middles ware can be seen here http://expressjs.com/4x/api.html#app.use , the documentation is self explanatory.