A SSG caching mechanism for NextJS to share data between getStaticPaths and getStaticProps
This project is an implementation of an idea to allow data to be shared between routes in NextJS SSG. It is a Next.js project that fetches data from Contentful at build time using Static Site Generation (SSG). The purpose of this solution is to separate the data fetching from Contentful and Next’s SSG, allowing the content to be fetched upfront, cached on the file system, and reused for subsequent calls from getStaticPaths or getStaticProps.
To install and use this project, follow these steps:
npm install to install the necessary dependencies..env.sample and rename it to .env.local. This file contains the environment variables required for the project.CONTENTFUL_SPACE_ID, CONTENTFUL_MANAGEMENT_API_ACCESS_TOKEN, and CONTENTFUL_ACCESS_TOKEN in the .env.local file. These values can be obtained from your Contentful Space’s API Keys.CONTENTFUL_ACCESS_TOKEN is required to fetch data at build time.CONTENTFUL_MANAGEMENT_API_ACCESS_TOKEN is used to generate the Typescript definitions specific to your space schema. If you are not using Typescript, this is not required../contentful/sample-import.json if you want to run the application as-is. You can follow the Contentful Import steps provided.npm run dev to generate the Typescript definitions, start the local NextJS server, and fetch data as requested.http://localhost:3000 and navigate around to see the data being fetched and cached accordingly. In the terminal, you will see if it was a cache hit or if Next had to go to Contentful.npm run build. This will generate the Typescript definitions, clear out the local file-system cache, and statically generate the application by fetching and caching data from Contentful as needed.This project provides a solution to the problem of data sharing between routes in NextJS SSG. By fetching data from Contentful at build time and caching it on the file system, it reduces the need for multiple API calls and improves the efficiency of data fetching. With the ability to separate the data fetching process from Next’s SSG, it enables developers to fetch content upfront, cache it, and reuse it for subsequent calls, resulting in improved performance and a better user experience.