How to avoid repeated API call across an entire NextJS application?

Viewed 436

This seems like a really simple thing to do, yet I am having trouble finding the right architecture to do this.

Here's the scenario:

  • We have an API route api/templates that should, in theory, happen in every single route/page of the App. It fetches all the different templates and all the data in the app belongs to one of those templates. These are dynamic and can change over time, so they are not an 'importable JSON'
  • Every page should get these assets on load, but...
  • once it's loaded, and you start navigating through pages, the app should NOT re-fetch them on every single page navigation
  • We will implement a socket notification to alert an already-loaded client when templates change in the database

The problem is that, since this is needed on every page, SSR still needs to be able to access this on every page and our SEO policy requires server side rendering to send these pages fully rendered to client.

So, what we are looking for is:

  • to have a somewhat 'conditional' getServerSideProps that, if it is a full reload, it fetches that, but, if it is already in the client's memory, it skips that
  • we have looked into SWR, which, in theory, would work, but it still makes the API call as an after-thought, helping on the client side, but defeating the objective of not actually making the call, so that the backend is not 'burdened' with an unnecessary call

Honestly, this looks like a very 'common' pattern, yet I have completely failed to achieve a proper solution within the NextJS app environment. Maybe it's an "anti-pattern" and we shouldn't be doing this?

0 Answers
Related