How to Cache Data in Next.js Globally Across All Pages at Build Time
When working on a Next.js-based website, you might encounter the need to fetch data from an API at build time. In this article, I’ll share a solution that works both in development (localhost) and in production (Vercel) environments.
Let’s consider a scenario where we have a list of “members” and we want to download this data once, store it, and make it available across all pages. The list of members is relatively static and changes at most once a day. If any changes occur, we can programmatically trigger a redeploy using Vercel’s Deploy Hooks.
Here’s the plan:
- Create a local cache file named
.members
to store the data. - Implement a function in the
lib/members.js
file to fetch and store the data in the cache as JSON. - Read the data from the cache when needed.
First, let’s create the lib/members.js
file with the following code:
1 | import fs from 'fs' |
To use the getMembers()
function in any page, import it with the following code:
1 | import getMembers from 'lib/members' |
Inside the getStaticProps()
function, fetch the members data using await getMembers()
:
1 | const members = await getMembers() |
Now, you can use the members
data in various ways within your page components. For example, you can add it to the props
object returned by getStaticProps
and iterate over it in the page component like this:
1 | {members?.map((member) => { |
That’s it! With this approach, you can cache data globally across all pages in Next.js at build time, ensuring efficient data retrieval and usage.
tags: [“Next.js”, “caching”, “static data”, “build time”, “API”, “Vercel”]