We now have a youtube channel. Subscribe!

Express.js | Middleware

Express.js | Middleware


Hello folks! Welcome back to a new edition of our tutorial on ExpressJS. In this section of our tutorial on Express, we'll be studying about Express.js Middleware.

Middleware functions are functions that've access to the request object, the response object, and the next middleware function in the application's request-response cycle. These functions are used to modify req and res objects for task such as parsing request bodies, adding response headers, etc.

Example

Below is a simple example of a middleware function -

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);

The above middleware function is called for every request on the server. So after every request, we will get the following message in the console -

A new request received at 1467267512545

To restrict it to a particular route (and all its subroutes), provide that route as the first argument of app.use().

Example

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 will log the time.


Order of Middleware Calls

One of the most important things about middleware in Express is the order in which they are written/added in your file; the order in which they're executed, provided that the route matches also needs to be considered.

Example

In the following example, the first function runs first, then the route handler and finally the end function. This example summarizes how to make use of middleware before and after route handler; also how a route handler can be used as middleware itself.

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

//First middleware before response is sent
app.use(function(req, res, next){
   console.log("Start");
   next();
});

//Route handler
app.get('/', function(req, res, next){
   res.send("Middle");
   next();
});

app.use('/', function(req, res){
   console.log('End');
});

app.listen(3000);

When we visit '/' after running this code, we receive the response as Middle and on our console -

Start
End

Diagrammatic Representation of Middleware

Following diagram summarizes what we've learnt about middleware -

middleware_description

Now that we have known how to create our own middleware, let us discuss about some of the most commonly utilized middleware created within the community.


Third Party Middleware

A list of third party middleware for Express is available here. Following are some of the most commonly used middleware; we'll also learn how to use/mount these -

body-parser

This is used to parse the body of requests which have payloads attached to them. To mount body parser, we need to install it via npm install-- save body-parser and to mount it, include the following lines in your index.js -

var bodyParser = require('body-parser');

//To parse URL encoded data
app.use(bodyParser.urlencoded({ extended: false }))

//To parse json data
app.use(bodyParser.json())

To see all available options for body-parser, visit its GitHub page.

cookie-parser

This middleware parses Cookie header and populate req.cookie with an object keyed by cookie names. To mount cookie parser, we need to install it utilizing npm install -- save cookie-parser and to mount it, include the following lines in your index.js -

var cookieParser = require('cookie-parser');
app.use(cookieParser())

express season

This creates a season middleware with the given options. We'll discuss about its usage in the Seasons tutorial.

We have many other third party middleware in ExpressJS. However, we have discussed only a few vital ones here.


Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we are going to be studying about Express.js Templating.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2023 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain