user548084
user548084

Reputation: 499

NodeJS Express: Pattern for common data elements on every page

Is there a recommended pattern for page elements that are persistent and common across all pages on a site? For instance, a "total units sold" on the top of every page. You would cache that value and update the cache every hour or so, but where would you actually retrieve this value and pass it to the view in the express web request?

In PHP you have to use a key-store, but since node is persistent across requests it seems like you would keep the value in memory, but where?

A couple thoughts:

1) In the app object from express() and pass to view with render. I think app.locals is designed for this, but app.locals can't be accessed from within the route handler.

2) Use a cache and pass it to view with render - I don't like that I have to explicitly call cache.getCommonValues in every route handler, extend the object, and pass it again in render.

3) Hack into the renderer and extend every data object with common stuff - Elegant maybe, but how to access the values to update them with a cronjob or when you just want to check one in the route handler. Also not sure exactly how to hack the renderer, mustache in this case...

4) Store it in the session - Might get big, hard to update reliably.

Any other thoughts?

Upvotes: 1

Views: 262

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146014

app.locals is fine for this, and yes it is available in the route handler via res.app.locals. Both the request and the response have access to each other as well as the app instance.

Upvotes: 2

Related Questions