Express: Middleware

 

= functions that have access to request object(req) and response object (res) and the next middleware function in the layer (if more than one specified) . The next middleware function is commonly denoted by a variable named next.

Middleware allows you to define a stack of actions that you should flow through.

  • A layer in middleware stack = function which takes as parameters: req, res and next function

 

app.use() = specify middleware to execute (can call multiple times)

this function is called FOR ALL requests. Notice that the function it calls "myLogger" has important line next() that means it will go on to be processed by
app.get or any other methods implemented.

 

EXAMPLE 1: middleware that is called ALWAYS regardless of URI request

var express = require('express');
var app = express();


//Simple request time logger
app.use(function(req, res, next){
 	console.log("A new request received at " + Date.now());
 	//This function call is very important. It tells that more processing is
   	//required for the current request and is in the next middleware function/route handler.
  	next();  });


app.listen(3000);

 

 

EXAMPLE 2: if have a get request for / will first execute then go to app.get handler

var express = require('express')
var app = express()
var myLogger = function (req, res, next) {
    console.log('LOGGED')
    next()  }

 app.use(myLogger)
 app.get('/', function (req, res) {
    res.send('Hello World!')  })


app.listen(3000)

 

 

EXAMPLE 3: where you call middleware only if URI is /things then will go next to app.get handler code

 

var express = require('express');
var app = express();

//Middleware function to log request protocol
app.use('/things', function(req, res, next){
  	console.log("A request for things received at " + Date.now());
  	next();  });


//Route handler that sends the response
  app.get('/things', function(req, res){
  	res.send('Things');	  });

app.listen(3000);

Now whenever you request any subroute of '/things', only then it'll log the time.

 

 

Multiple Layers in Middleware --> MULTIPLE calls to app.use()

 

 

Third Party -already created middleware in Express you can call app.use to setup

A list of Third party middleware for express is available here. Following are some of the most commonly used middlewares, and how to use/mount these:

© Lynne Grewe