adrianvlupu
adrianvlupu

Reputation: 4628

Passing an object from middleware to an express route

I'm looking for an elegant solution to send data from a middleware function to the subsequent routes.

I guess I can add a property to req, but it doesn't feel right. Is there a better way?

app.post('/', filter);

var filter = function (req, res, next) {
    req.something = {};
    next();
};

Upvotes: 4

Views: 3628

Answers (1)

Naeem Shaikh
Naeem Shaikh

Reputation: 15725

Though you ask for attaching data to req, but You can attach the data to res object using res.locals:

app.post('/', filter);

var filter = function (req, res, next) {
    res.locals.myVar = 'myVal'; // data attched to response
  res.locals.myOtherVar = 'myOtherVal';
    next();
};

and this data will only be available throughout the request lifetime. i.e for that single request(so I think wont matter if you attach the data to res object in this case)

Upvotes: 4

Related Questions