How to share data between API route and getServerSideProps?

Viewed 506

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:

  1. a client request requires x and
  2. my cached data of x is older than ttl seconds.

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 x and save it as Provider.x if Provider.x is undefined or the previous fetch is longer than ttl seconds 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.

1 Answers

You could use Node.js global object to share data between API routes and getServerSideProps.

For instance, you could set the data in the getServerSideProps function.

export const getServerSideProps = async () => {
    // Set data in `global` object
    global._SOME_DATA_ = { data: { hello: 'world' }, ttl: '3600' }
    // ...
}

Then retrieve that same data at a later point in the API route.

export default async (req, res) => {
    console.log(global._SOME_DATA_) // Logs: `{ data: { hello: 'world' }, ttl: '3600' }`
    // ...
}
Related