cache data from getinitialprops

cache data from getinitialprops

getInitialProps is used to fetch data for the page but it also fires when the user presses the back button on the browser. This causes the browser to scroll to the position where you previously left off but without the remote data from getInitialProps needed to render.

Copy Snippet
let cache = {};

class App extends React.Component {
  static async getInitialProps({ req, query, asPath, pathname }) {

    let data;
    //if data is in cache then use the cache
    if (cache[someID]) {
      data = cache[someID]
    } else {
      //if not, then fetch from server
      data = await fetch(`someAPI`);
    return { data }

  render() {
      //check if client, if so store the data in the cache. 
      //If you don't do this check, there will be a separate cache stored on the server since Next.js does server side rendering as well.
      if (process.browser) {
        cache[someID] =;
      return (

export default App;