Nextjs Ssg Contentful Cached screenshot

Nextjs Ssg Contentful Cached

Author Avatar Theme by Jrandeniya
Updated: 27 Jan 2022
12 Stars

A SSG caching mechanism for NextJS to share data between getStaticPaths and getStaticProps

Categories

Overview

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.

Features

  • Shared data between routes: Allows data to be shared between routes in NextJS SSG.
  • Efficient data fetching: Fetches data from Contentful at build time, reducing the need for multiple API calls.
  • File system caching: Caches the fetched data on the file system for subsequent reuse.

Installation

To install and use this project, follow these steps:

  1. Run npm install to install the necessary dependencies.
  2. Make a copy of .env.sample and rename it to .env.local. This file contains the environment variables required for the project.
  3. Set the values for 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.
  4. Optionally, import the Contentful schema and data from ./contentful/sample-import.json if you want to run the application as-is. You can follow the Contentful Import steps provided.
  5. Run npm run dev to generate the Typescript definitions, start the local NextJS server, and fetch data as requested.
  6. Visit 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.
  7. For building the application, run 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.

Summary

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.