NextJS Custom Server - supply app-level cache to requests?

Viewed 465

Our NextJS react server makes frequent queries to a backend to get collections of data that infrequently change. For instance, collections of values like site configurations, i18n labels, etc. It occurred to me we could just cache that collection of data on the SSR side, and then at the request level, the SSR side could check the cache, and only query the backend if the cache expires. This would reduce calls against our backend API considerably. (This is server-side-only behavior, it would not impact the browser-side.)

The point is that a request-level cache isn't sufficient. It would defeat the purpose. So it needs to be an app-level cache that initializes at server startup. (I'm thinking of an in-memory cache like node-cache.) And, it can't be a cache that operates only at the custom-server level outside of NextJS, since the usage of it depends on request-level information - the app-level cache needs to be available while NextJS SSR processes the request.

But I'm not sure how to supply the cache to the request level, so functions like getServerSideProps can access it. In the NextJS custom server, I'm tempted to create some sort of a context object that can be passed to next, but in the request handler:

const handle = nextApp.getRequestHandler();
...
nextAppRequestHandler(req, res);

There doesn't seem to be a way to pass along additional parameters like context.

What would be the best practice here? For a global store like this, should I extend or add it to the request object itself? I guess more generally this is a question about supplying application-scoped singletons to SSR NextJS requests.

0 Answers
Related