How to pass variables to the next middleware using next() in Express.js?

Sometimes, we want to pass variables to the next middleware using next() in Express.js.

In this article, we’ll look at how to pass variables to the next middleware using next() in Express.js.

How to pass variables to the next middleware using next() in Express.js?

To pass variables to the next middleware using next() in Express.js, we can add the data to the res object.

For instance, we write

app.use((req, res, next) => {
  res.locals.user = req.user;
  res.locals.authenticated = !req.user.anonymous;
  next();
});

app.use((req, res, next) => {
  if (res.locals.authenticated) {
    console.log(res.locals.user.id);
  }
  next();
});

to set res.locals to some values in the first middleware.

And then we call next to call the next middleware function.

Then in the 2nd middleware, we check the values that we set as properties of res.

Conclusion

To pass variables to the next middleware using next() in Express.js, we can add the data to the res object.