Retrieve data server side and save in context with Next.js

In Next.js, there's no native function to a) retrieve data from an API, b) do it on the server, c) make it available on every page, and d) only query the API on the first page the user visits.

As you've found out, getInitialProps and getServerSideProps will run every time you visit that page.

However, we can get this to work.

If you need the data before the initial load

  1. Use getInitialProps in _app.js to retrieve data from the API
  2. Load the data into React context inside the _app.js file so it persists between pages
  3. When the browser gets the data, create a cookie.
  4. On a subsequent page load, in getInitialProps, check if there's a cookie. If so, don't retrieve the data.

There's a fairly popular library called nookies to help with cookies in a Next.js project.

If you can load the page then fetch the data

There is a performance cost to using getInitialProps in _app.js: you'll never be able to create a fully static page. That's because getInitialProps will have to run on every single page load.

If you can fetch the data after page load, add an API route. Then, in the context provider, use useEffect to fetch the data.


Maybe Redux could be a solution for your issues. Context api tends to trigger unnecessary re rendering of the consumers.