0
0
NextjsDebug / FixBeginner · 4 min read

How to Fix Caching Issue in Next.js Quickly and Easily

To fix caching issues in Next.js, ensure you properly configure cache headers or use Incremental Static Regeneration (ISR) with revalidate. Also, clear stale caches and avoid aggressive browser caching to serve fresh content.
🔍

Why This Happens

Caching issues in Next.js often happen because the browser or CDN keeps serving old versions of your pages or assets. This can occur if cache headers are set too long or if static pages are not updated properly after deployment.

For example, if you use getStaticProps without revalidation, the page is built once and cached forever until you redeploy.

javascript
export async function getStaticProps() {
  const data = await fetch('https://api.example.com/data').then(res => res.json());
  return {
    props: { data },
    // No revalidate means page is cached indefinitely
  };
}
Output
Page content stays the same even if API data changes until next deployment.
🔧

The Fix

To fix caching, add the revalidate property in getStaticProps to enable Incremental Static Regeneration (ISR). This tells Next.js to refresh the page after a set number of seconds.

Also, for API routes or server responses, set proper cache-control headers to control browser and CDN caching.

javascript
export async function getStaticProps() {
  const data = await fetch('https://api.example.com/data').then(res => res.json());
  return {
    props: { data },
    revalidate: 60, // Regenerate page every 60 seconds
  };
}

// Example of setting cache headers in API route
export default function handler(req, res) {
  res.setHeader('Cache-Control', 'public, max-age=60, stale-while-revalidate=30');
  res.json({ time: Date.now() });
}
Output
Page updates every 60 seconds with fresh data; API responses cached for 60 seconds.
🛡️

Prevention

To avoid caching issues in the future, always use revalidate with static props when data changes frequently. Avoid setting overly long cache durations on headers.

Use tools like browser DevTools to inspect cache headers and clear caches when testing. Automate cache busting by including versioning in asset URLs.

⚠️

Related Errors

Similar caching problems include stale API data, outdated static assets, and service worker caching issues. Quick fixes include clearing browser cache, invalidating CDN caches, and updating cache headers.

Key Takeaways

Use revalidate in getStaticProps to refresh static pages automatically.
Set proper Cache-Control headers on API responses to control caching behavior.
Avoid long cache durations unless content is truly static and unchanging.
Use browser DevTools to check and clear caches during development.
Version static assets to force cache updates when content changes.