NodeJS/Express: implicitly push data from custom middleware into render call

NodeJS/Express: implicitly push data from custom middleware into render call

Problem

I’m using NodeJS/Express3.

I have some custom middleware which retrieves some data from a database, based on cookie and URL.

I want to have access to this data in the base template (used for all pages).

I can do this explicitly by attaching the data to the req, and then using res.render('template', {foo: req.foo, ...page specific data...});

I want to make this implicit, so as I add (or remove) custom middleware I don’t have to change every render call.

  • Is there a way of making data from custom middleware available to render without having to add it to req and explicitly pass it through every single render request.

I’m using LinkedIn’s version of dust.js templates, but I think the question is template engine agnostic.

Problem courtesy of: chrisdew

Solution

I think the answer may lie in res.locals. http://expressjs.com/api.html#res.locals

Solution courtesy of: chrisdew

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *