Suppose need to fetch non-client specific data x from an external API. To reduce loading time, I want to fetch x once, cache it and only fetch it again when:
- a client request requires
xand - my cached data of
xis older thanttlseconds.
How do I achieve this in a way I can access the cached data of x from both an API route as well as getServerSideProps?
My approaches
x as a static class property
I created a class Provider with a static method getX that will
- fetch
xand save it asProvider.xifProvider.xis undefined or the previous fetch is longer thanttlseconds old and then - return
Provider.x.
This does not work, since Provider.x in getServerSideProps and Provider.x in the API route do not point to the same object in memory. I suppose this is due to them running in individual workers.
Saving x to a file
Similar to the first approach, except saving x to a local file rather than a static property. This does work, but is very slow as it has to read and write on the hard disk instead of in memory.