How to Opt Out of Cache in Next.js for Fresh Data
To opt out of cache in Next.js, use
fetch with the option { cache: 'no-store' } to always get fresh data. For server-side rendering, set revalidate: 0 in getStaticProps or use no-cache headers in API routes to prevent caching.Syntax
Next.js allows you to control caching behavior mainly through fetch options and data fetching methods like getStaticProps. Here are key parts:
fetch(url, { cache: 'no-store' }): Fetch fresh data every time, bypassing cache.getStaticProps() with: Disable static regeneration cache, forcing fresh data on every request.revalidate: 0- API routes can send
Cache-Controlheaders likeno-cacheto prevent caching.
javascript
export async function getStaticProps() { const res = await fetch('https://api.example.com/data', { cache: 'no-store' }); const data = await res.json(); return { props: { data }, revalidate: 0 // disables ISR cache }; }
Example
This example shows a Next.js page fetching fresh data on every request by opting out of cache using fetch with cache: 'no-store' and disabling ISR with revalidate: 0.
javascript
export default function Page({ data }) { return ( <main> <h1>Fresh Data</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </main> ); } export async function getStaticProps() { const res = await fetch('https://api.example.com/data', { cache: 'no-store' }); const data = await res.json(); return { props: { data }, revalidate: 0 // disables caching }; }
Output
<main>
<h1>Fresh Data</h1>
<pre>{...latest JSON data from API...}</pre>
</main>
Common Pitfalls
Common mistakes when trying to opt out of cache in Next.js include:
- Not setting
cache: 'no-store'infetch, so data is cached by default. - Using
revalidatewith a positive number, which enables ISR caching. - Forgetting to set proper
Cache-Controlheaders in API routes, causing browser or CDN caching.
Always verify your fetch options and headers to ensure caching is disabled.
javascript
/* Wrong: fetch without cache option caches data */ const res = await fetch('https://api.example.com/data'); /* Right: fetch with no-store disables cache */ const resNoCache = await fetch('https://api.example.com/data', { cache: 'no-store' });
Quick Reference
| Method | How to Opt Out of Cache | Effect |
|---|---|---|
| fetch | { cache: 'no-store' } | Always fetch fresh data, no cache used |
| getStaticProps | revalidate: 0 | Disables ISR, regenerates page on every request |
| API Routes | Cache-Control: no-cache header | Prevents browser/CDN caching of API responses |
Key Takeaways
Use fetch with { cache: 'no-store' } to bypass Next.js and browser cache.
Set revalidate: 0 in getStaticProps to disable static regeneration caching.
Add Cache-Control: no-cache headers in API routes to prevent caching.
Without these settings, Next.js and browsers may serve cached data.
Always test your page to confirm fresh data is loaded as expected.