0
0
NextjsHow-ToBeginner · 4 min read

How to Cache API Response in Next.js for Faster Pages

In Next.js, you can cache API responses by using getStaticProps to fetch data at build time or getServerSideProps with caching headers for server-side caching. Additionally, you can use revalidate in getStaticProps to update cached data periodically without rebuilding the whole site.
📐

Syntax

Next.js provides two main ways to fetch and cache API data for pages:

  • getStaticProps: Runs at build time, caches data as static HTML, optionally revalidates after a set time.
  • getServerSideProps: Runs on each request, can use HTTP cache headers to cache responses.

Example syntax for getStaticProps with revalidation:

javascript
export async function getStaticProps() {
  const res = await fetch('https://api.example.com/data')
  const data = await res.json()

  return {
    props: { data },
    revalidate: 60 // seconds to wait before regenerating the page
  }
}
💻

Example

This example shows how to cache an API response in Next.js using getStaticProps with a revalidation time of 10 seconds. The page will serve cached data and update it in the background every 10 seconds.

javascript
import React from 'react'

export default function DataPage({ data }) {
  return (
    <main>
      <h1>Cached API Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </main>
  )
}

export async function getStaticProps() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts/1')
  const data = await res.json()

  return {
    props: { data },
    revalidate: 10 // cache for 10 seconds
  }
}
Output
<main> <h1>Cached API Data</h1> <pre>{"userId":1,"id":1,"title":"...","body":"..."}</pre> </main>
⚠️

Common Pitfalls

Common mistakes when caching API responses in Next.js include:

  • Not setting revalidate in getStaticProps, causing stale data.
  • Using getServerSideProps without proper cache headers, leading to no caching.
  • Fetching data inside the component instead of data fetching methods, which disables static caching.

Example of wrong and right usage:

javascript
/* Wrong: Fetching inside component disables caching */
import React from 'react'

export default function Page() {
  const [data, setData] = React.useState(null)
  React.useEffect(() => {
    fetch('https://api.example.com/data')
      .then(res => res.json())
      .then(setData)
  }, [])

  if (!data) return <p>Loading...</p>
  return <pre>{JSON.stringify(data)}</pre>
}

/* Right: Fetching in getStaticProps enables caching */
export async function getStaticProps() {
  const res = await fetch('https://api.example.com/data')
  const data = await res.json()
  return { props: { data }, revalidate: 60 }
}

export default function Page({ data }) {
  return <pre>{JSON.stringify(data)}</pre>
}
📊

Quick Reference

MethodWhen It RunsCaching BehaviorUse Case
getStaticPropsBuild time + optional revalidationStatic HTML cached, updates after revalidate secondsBest for mostly static data
getServerSidePropsEvery requestNo built-in caching, use HTTP cache headersDynamic data needing fresh fetch
Client-side fetchIn browser after loadNo Next.js caching, manual caching neededUser-specific or frequently changing data

Key Takeaways

Use getStaticProps with revalidate to cache API responses and update them periodically.
Avoid fetching data inside components if you want Next.js to cache the response.
Use getServerSideProps with cache headers for server-side caching on each request.
Set proper revalidation times to balance freshness and performance.
Client-side fetching does not benefit from Next.js static caching.