Categories: Express JS

Express Middleware No.1 Easy Tutorial

Express Middleware comes between request and response. When a request is made, it is received by the server where middleware performs its tasks on the received request and then route handler sends the response which again passes through middleware functions and in the end reaches to the client.

These functions have access to requests, responses and next middleware function in request-response cycle. Middleware modifies the request and response objects. For example, when parsing requests, headers, or responses are added, middleware works. Middleware can be route specific as well as generic.

For example, if you want to get a date at each request made to the server, you will need generic middleware rather than route specific. Example code is given below.

//imports express module
let express = require('express');
//initializes express app
let app = express();

//request response cycle 
app.use(function(req, res, next){
    console.log("A request has been received at " + Date.now());
    
    //this function tells us that more processing is needed for current   
    //request and next middleware.
    next();
 });
 
//listens to server at port 3000
app.listen(3000);

Whenever a request is made to any route, it will give the date and time for the request made.

To make it route specific, we will add route to app.use() as first argument and define the route handler later to send the response.

//imports express module
let express = require('express');
//initializes express app
let app = express();

//request response cycle 
app.use('/', function(req, res, next){
    console.log("A request has been received at " + Date.now());
    
    //this function tells us that more processing is needed for current request and next middleware.

    next();
 });
 
    //request handler for sending response
 app.get('/', function(req, res){
   
    res.send('Success!');
 });

//listens to server at port 3000
app.listen(3000);

Express Middleware Calls Order in Node Express JS

Middleware functions are executed in order in which they are defined. For example, in the above code app.use() executes first and then app.get() executes. If I modify the above code as below.

//imports express module
let express = require('express');
//initializes express app
let app = express();

//request response cycle 
app.use('/', function(req, res, next){
    console.log("A request has been received at " + Date.now());
    
    //this function tells us that more processing is needed for current request and next middleware.

    next();
 });
 
    //request handler for sending response
 app.get('/', function(req, res, next){
   
    res.send('Success!');
    next();
 });

 app.use('/', function(req, res){
     console.log('Ended successfully!')
 });
//listens to server at port 3000
app.listen(3000);

app.use() will execute, then app.get() will execute and in the end app.use() will execute and print Ended successfully! on console. After accessing http://localhost:3000/, the following output gets printed on console.

Express Middleware developed by 3rd Party

Express JS supports middleware provided by 3rd party for various purposes. You can find all the middleware from http://expressjs.com/en/resources/middleware.html. Most we use some middleware like cookie-parser, cookie-session, multer, serve-static, timeout, response-time, body-parser, compression etc.

Some 3rd Party Middleware compatible with Express JS


body-parser
This middleware helps in parsing HTTP request body.
compression This middleware helps in compressing HTTP responses.

cookie-parser
This middleware helps in parsing cookie header to populate request.cookies.  
csurf   This middleware helps in protecting from CSRF exploits.
multer It is used when we have to handle multi-part form for uploading files.
session   This middleware is used in establishing server-based sessions. Mostly it is used in development only because in production we prefer to use cookie based sessions.    

response-time  
This records HTTP response time which helps us in improving our application.  

Each of the middleware is installed by executing command.

$ npm install --save <middleware name>

To use any, you will import it in your index.js file and the use app.use() method. For example, cookie-parser can be used as:

//imports express module
let express = require('express');
//initializes express app
let app = express();

let cParser = require('cookie-parser');

app.use(cParser())

//listens to server at port 3000
app.listen(3000);

In this tutorial, you have learnt about Express Middleware. In the next tutorial, you will learn about Frontend Templating in Express JS using Pug Engine.

Arslan ud Din Shafiq

Alibaba Cloud MVP, Alibaba Cloud Technical Author, Dzone MVB, Software Engineer, Software Developer, Software Designer, Web Engineer, Web Developer, Web Designer, Database Designer, Database Developer, Cloud Computing Specialist, Linux Expert, Servers, 3D Modeling, Blogger, Facebook Map Editor, Google Map Editor

Share
Published by
Arslan ud Din Shafiq

Recent Posts

How To Set Up Secure Nginx Server Blocks on Ubuntu 22.04

NGINX Server Nginx, a popular open-source web server, excels at handling high traffic websites efficiently.… Read More

1 week ago

The Web Server Showdown: Nginx vs. Apache, LiteSpeed, Caddy, and Beyond

In the realm of web hosting, choosing the right web server is paramount. It acts… Read More

1 week ago

Linear guidance systems

Are indispensable for ensuring smooth, precise linear motion in many industrial applications. Whether in robotics,… Read More

2 months ago

Cyber Attack Statistics – Identifying Vulnerabilities and Strengthening Defenses

Cyber attacks are becoming more frequent, complex, and damaging. They can disrupt critical operations and… Read More

3 months ago

Empowering Cybersecurity in 2024 with XDR for Comprehensive Threat Detection and Response

With the rise of new threats and the increasing complexity of IT environments, organizations need… Read More

3 months ago

Facade Design Pattern: Simplifying Complex Systems

1. Introduction In software design, managing complex systems can be challenging. The Facade Design Pattern… Read More

5 months ago