Persistent Handlebars context

I have an ExpressJS app which contacts a remote API and passes the results to a Handlebars template. That works nicely but the API is contacted every time the page is displayed, which is quite unnecessary.

For example: imagine the API returns user data (address, phone number etc). Once it has been retrieved and displayed, I should not need to hit the API again next time the user navigates to the same page.

Is there a way to check if the data has been previously retrieved from the API and have the template use a local copy, say, retrieved from a sessionStorage?

Cheers

As it turns out, I had part of the answer already. I was looking at the issue the wrong way. I wanted my Handlebars template to do something is it not meant to do.

The answer is indeed to use sessionStorage, but that is set in my Node/Express code. So, the first time the page is loaded, there is no sessionStorage set, the route executes code to fetch data from the API, passes it to my Handlebars template and creates the sessionStorage.

Next time the page is accessed, the sessionStorage is already set and Node/Express sends that info to Handlebars without accessing the API.

In the end, all I needed was a nudge to the right direction. :man_shrugging:

1 Like

Agreed! That is probably the best way to accomplish it. If you want to persist the data longer, you could also use localStorage. Also, are you checking to see if the the data on the server is more recent and forcing an API call if the data is indeed more recent on the server?

:desert_island:

For the sake of those with similar doubts,I should add something else I have learned: localStorage and sessionStorage are browser only storages. They are used in the front-end and NOT something we set on the server side using Node/Express.

I managed to solve my problem using the express-session module for NodeJs, first alone, storing the info in memory for testing purposes, and then coupling it with the connect-mongo module to store it in MongoDB.

We live and learn. To me, that is the fun part of programming! ¯_(ツ)_/¯

1 Like