How to Fix Caching Issue in Next.js Quickly and Easily
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.
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 }; }
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.
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() }); }
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
revalidate in getStaticProps to refresh static pages automatically.Cache-Control headers on API responses to control caching behavior.