Open In App

What is middleware chaining in Express JS, and how is it useful?

Last Updated : 12 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Express JS there is the process of Middleware chaining by which multiple middleware functions sequentially can be processed and also can be able to modify the incoming requests before they reach the final route handler. In this article, we will see the concept of Middleware Chaining in Express JS with a proper example demonstration.

Prerequisites

What is Middleware Chaining?

Middleware Chaining is the concept where multiple middleware functions are applied in sequential order till they reach the final route handler. Here, each of the middleware functions performs certain tasks like data processing, logging, authentication, etc. Each of the middleware functions can able to modify the request or response objects, terminate the request-response cycle, or pass control to the next middleware using the next() function.

Syntax

const middleware1 = (req, res, next) => {
// Tasks
next();
};
const middleware2 = (req, res, next) => {
// Tasks
next();
};
app.get('/example', middleware1, middleware2, (req, res) => {
// Route handler
});

How is Middleware Chaining Useful?

Middleware Chaining in Express.js is useful because it allows a modular and organized approach to managing and handling HTTP requests and responses. Below are some of the points that state why Middleware Chaining is useful in Express.js.

  • Modularity: In the middleware function there are units of functionality that are independent, so due to this the managing and organizing of code become easier. Also, they have been reused across various routes or applications.
  • Sequential Execution: The order of Middleware functions execution is sequential. This sequential order allows developers to properly control the overall flow of the request-response cycle and also performs the functional tasks in a specific order.
  • Error Handling: Middleware Chaining allows error handling where if an error occurs during the request-response tasks then the middleware function can call the next function with the error object and execute the error-handling middleware.
  • Authentication and Authorization: The middleware functions are also used for implementing authentication and authentication. These middleware functions can be chained together to perform the different levels of access control within the application.

Steps to use middleware chaining in Express JS

Step 1: In the first step, we will create the new folder as a a middle-chain by using the below command in the VScode terminal.

mkdir middle-chain
cd middle-chain

Step 2: After creating the folder, initialize the NPM using the below command. Using this the package.json file will be created.

npm init -y

Step 3: Now, we will install the express dependency for our project using the below command.

npm i express

Step 4: Now create the below Project Structure of our project which includes the file as app.js.

Project Structure:

4

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.18.2"
}

Example: Write the following code in App.js file

Javascript




//App.js
 
const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: true }));
// middleware function 1
const reqFunction = (req, res, next) => {
    console.log(`Received a ${req.method} request to ${req.url}`);
    next();
};
// middleware function 2
const formDataFunction = (req, res, next) => {
    const { name: geekName } = req.body;
    if (geekName) {
        req.username = geekName;
    }
    next();
};
// middleware function 3
const userShowFunction = (req, res) => {
    const username = req.username || 'Guest';
    res.send(`<h1>Hello, ${username}!</h1>`);
};
// route handler with middleware chaining
app.get('/', reqFunction, (req, res) => {
    res.send(`
    <form method="post" action="/msg" style="margin-top: 20px;">
      <label for="name">Enter your name:</label>
      <input type="text" id="name" name="name" required>
      <button type="submit">Submit</button>
    </form>
  `);
});
app.post('/msg', reqFunction, formDataFunction, userShowFunction);
// Starting the server
const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});


Step To run the application:

Step 1: Start the server by using the below command.

node app.js

Output:

Output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads