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
const express = require( "express" );
const app = express();
function middleware1(req, res, next) {
req.dataFromMiddleware1 = "Data of Middleware 1" ;
next();
}
function middleware2(req, res, next) {
console.log( "We are in Middleware 2." );
console.log(req.dataFromMiddleware1);
next();
}
app.get( "/" , middleware1, middleware2, (req, res) => {
return res.send(req.dataFromMiddleware1);
});
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