Skip to content
Related Articles

Related Articles

How to pass variables to the next middleware using next() in Express.js ?
  • Difficulty Level : Hard
  • Last Updated : 17 Feb, 2021
GeeksforGeeks - Summer Carnival Banner

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


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


// 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
function middleware2(req, res, next) {
  console.log("We are in Middleware 2.");
  // Get Data of Middleware1
  // Go to next middleware
// 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


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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :