Skip to content
Related Articles

Related Articles

Improve Article
How to pass variables to the next middleware using next() in Express.js ?
  • Difficulty Level : Hard
  • Last Updated : 17 Feb, 2021

The following example covers how to pass variables to the next middleware using next() in Express.js.

Approach:

We cannot directly pass data to the next middleware, but we can send data through the request object.

[Middleware 1] [Middleware 2]
request.mydata = someData; ——-> let dataFromMiddleware1 = request.mydata;

Installation of Express module:



You can visit the link Install express module. You can install this package by using this command.

npm install express

After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.

node index.js

Filename: index.js

Javascript




// Requiring module
const express = require("express");
const app = express();
  
function middleware1(req, res, next) {
  // Set data
  req.dataFromMiddleware1 = "Data of Middleware 1";
  
  // Go to next middleware
  next();
}
  
function middleware2(req, res, next) {
  console.log("We are in Middleware 2.");
  
  // Get Data of Middleware1
  console.log(req.dataFromMiddleware1);
  
  // Go to next middleware
  next();
}
  
// Handling Get Request '/'
app.get("/", middleware1, middleware2, (req, res) => {
  return res.send(req.dataFromMiddleware1);
});
  
// Server Setup
app.listen(5000, () => {
  console.log(`Server is up and running on 5000 ...`);
});

Steps to run the program:

Run the index.js file using the following command:

node index.js

Output: 

We will see the following output on the console:

Server is up and running on 5000 ...

Now open the browser and go to http://localhost:5000/, you will see the following output on screen:

Output on Browser

Now again check the terminal output, it will look like the following: 

Server is up and running on 5000 ...
We are in Middleware 2.
Data of Middleware 1
My Personal Notes arrow_drop_up
Recommended Articles
Page :