Is it OK to add data to the response object in a middleware module in Express.js?

It is perfectly OK. It is how JavaScript is designed. Only thing you should be careful is to not accidentally overriding already existing properties or being overridden by others. To be safer, instead of adding everything directly to req/res objects, you might consider going a level deeper:

res.mydata={}
res.mydata.person= ...

Like that.


I know this is an old thread, but there is something else to add to this topic.

Express has a response.locals object which is meant for this purpose - extending the response from middleware to make it available to views.

You could add a property directly to the response object, and as @hasanyasin indicated, is how JavaScript is designed. But Express, more specifically, has a particular way they prefer we do it.

This may be new in express 3.x, not sure. Perhaps it didn't exist when this question was asked.

For details, see

http://expressjs.com/en/api.html#res.locals

There is also an app.locals for objects which don't vary from request to request (or response to response I suppose).

http://expressjs.com/en/api.html#app.locals

See also: req.locals vs. res.locals vs. res.data vs. req.data vs. app.locals in Express middleware