I'm writing a Node/Express app (my first) and need help persisting what feels like a global variable across page loads; but using a global variable feels wrong.
For the purposes of the question, the site is essentially 3 different table views on the same data. The data in the tables is taken from 3 separate MongoDB tables, merged together with a function, and displayed (using Pug, iterating over the object I just created).
The 3 different views are just different Pug templates iterating over the same object.
I have middleware which generates this object from MongoDB and stores it on res.locals
, but I don't want to re-generate it by default every time the user selects a different view. The data hasn't changed, and this feels wasteful.
I want to be able to set some sort of variable, dataNeedsToBeUpdated
, and if true
then the function inside my middleware will actually do the work and regenerate the table; if false
, it'll just skip the operation.
If the user performs one of my update operations, I'll set dataNeedsToBeUpdated = true
, redirect, middleware will fire, and the data will refresh before the next page load.
How do I do this properly?
app.locals
works just about like res.locals
, just it's available to the whole app. You can access it in middleware from req.app.locals
. The flow as you've described it sounds good; just use app.locals
for storing the data and the dataNeedsToBeUpdated
.