Search code examples
javascriptcachingnext.jsserver-side-rendering

Implementing data fetch caching within nextjs getServerSideProps()


I am building an application using nextjs, which accesses data from a firebase firestore. Currently it makes these request on every page load, but on certain pages where the data doesn't have to be fully up to date, I want to implement some form of caching mechanism.

I have attempted to use the node-cache package, but it seems that each new HTTP request wipes this cache, as it is technically a new environment. I have also looked at adding cache headers within getServerSideProps(), but it doesn't seem to work, as each time the page is requested the function getPropertyPreviewData() is still being called.

I am unsure if there is something I am missing, or whether there is a simpler solution I haven't thought of. Any help would be much appreciated.

export const getServerSideProps = async (context) => {
  const { res } = context;
  res.setHeader(
    'Cache-Control',
    'public, s-maxage=600, stale-while-revalidate=1200'
  );

  const properties = await getPropertyPreviewData();
  return ({
    props: {
      properties
    }
  });
};

Solution

  • On second thought, it appears that this method of caching does work, but only when deployed in a production environment. When running locally with npm run dev the caching is disabled.