How to pass parameters between middleware in ExpressJS

Sometime ago I was wondering how to pass parameters between middleware in ExpressJS. Let’s see how:

First of all, skip to add properties the request or req object. Yes, it works in old versions but it will not work in the most recent versions of ExpressJS because it’s considered a bad practique.

Instead, use res.locals setting with res.locals.your_variable and then getting with res.locals.your_variable

How to pass parameters between middleware in ExpressJS

It's easy:

app.get('/test', 
  function(req, res, next) { 
    res.locals.custom   = true;
    res.locals.myObject = { hello: 1 };
    next(); 
  }, 
  function(req, res) { 
    console.log('See:', res.locals.custom, res.locals.myObject); 
    return res.status(200).send(res.locals); 
  });

Magic!

David Burgos

Read more posts by this author.