Cache data globally in Next.js at build time

By

Learn how to cache API data globally in Next.js at build time with a local JSON file, reading it from Server Components or from getStaticProps.

~~~

In my Next.js based website I had the need to fetch data from an API at build time.

I tried various solutions, nothing worked. Then after lots of research and trial and error, here’s what worked.

The solution works both on localhost (development) and on Vercel (production).

This is the scenario: I have the emails of the “members” stored somewhere. It can be a remote database, Airtable, anything.

I only want to download this data once, and then have it available on the website, until I trigger the next build.

This members list is very static. It might change once a day max. If this list changes, I will just programmatically trigger a redeploy on Vercel using their Deploy Hooks.

Here’s the plan. We’ll create a local cache of the data, in a .members file.

A function in the lib/members.js file will take care of fetching the data and storing it in the cache as JSON when it’s first called, and subsequently it will read the data from the cache:

import fs from 'fs'
import path from 'path'

function fetchMembersData() {
  console.log('Fetching members data...')
  return [{ email: '[email protected]' }, { email: '[email protected]' }]
}

const MEMBERS_CACHE_PATH = path.resolve('.members')

export default async function getMembers() {
  let cachedData

  try {
    cachedData = JSON.parse(
      fs.readFileSync(path.join(__dirname, MEMBERS_CACHE_PATH), 'utf8')
    )
  } catch (error) {
    console.log('Member cache not initialized')
  }

  if (!cachedData) {
    const data = fetchMembersData()

    try {
      fs.writeFileSync(
        path.join(__dirname, MEMBERS_CACHE_PATH),
        JSON.stringify(data),
        'utf8'
      )
      console.log('Wrote to members cache')
    } catch (error) {
      console.log('ERROR WRITING MEMBERS CACHE TO FILE')
      console.log(error)
    }

    cachedData = data
  }

  return cachedData
}

App Router (Next.js 16 default)

In the App Router you call that helper from a Server Component (or from a Route Handler under app/api), no getStaticProps needed. The page below doesn’t use any request-time API like cookies() or headers(), so Next.js prerenders it during next build, and the helper runs once, at build time, exactly like before:

import getMembers from 'lib/members'

export default async function MembersPage() {
  const members = await getMembers()

  return (
    <>
      {members?.map((member) => {
        return (
          <p key={member.email} className="mt-3">
            {member.email}
          </p>
        )
      })}
    </>
  )
}

If the data comes from a remote API you call with fetch(), you might not need the .members file at all, because Next.js can cache the request for you. Since Next.js 15 a fetch() in a Server Component is not cached by default, so you have to opt in with fetch(url, { cache: 'force-cache' }). With the Cache Components feature turned on (cacheComponents: true in next.config.js) you can also put the 'use cache' directive at the top of an async function and Next.js caches whatever it returns. For more on keeping server-only work off the client, see run code only on server or client in Next.js.

Pages Router (legacy)

On older Pages Router apps, import the same helper and call it inside getStaticProps():

import getMembers from 'lib/members'

export async function getStaticProps() {
  const members = await getMembers()

  return {
    props: {
      members,
    },
  }
}

Then iterate over members in the page component the same way as above.

Tagged: Next.js · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about next: