How to Use next.revalidate in fetch in Next.js for Data Caching
In Next.js, you can use
next: { revalidate: seconds } inside the fetch options to tell Next.js how often to refresh cached data. This makes your page fetch fresh data after the specified seconds, enabling Incremental Static Regeneration easily.Syntax
The next.revalidate option is added inside the fetch options object to control how often Next.js revalidates the cached response. It looks like this:
seconds: Number of seconds after which Next.js will re-fetch the data.
javascript
const res = await fetch(url, { next: { revalidate: 60 } // revalidate every 60 seconds });
Example
This example shows a Next.js server component fetching data with next.revalidate set to 10 seconds. The data will be cached and refreshed every 10 seconds automatically.
javascript
import React from 'react'; async function getData() { const res = await fetch('https://api.example.com/data', { next: { revalidate: 10 } // refresh data every 10 seconds }); return res.json(); } export default async function Page() { const data = await getData(); return ( <main> <h1>Data fetched with revalidate</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </main> ); }
Output
<main>
<h1>Data fetched with revalidate</h1>
<pre>{...json data...}</pre>
</main>
Common Pitfalls
Common mistakes when using next.revalidate include:
- Not placing
next: { revalidate }inside the fetch options object. - Using
revalidateoutside of server components or API routes where it has no effect. - Setting
revalidateto 0 or negative values, which disables caching.
Always ensure your fetch call is in a server context and the option is correctly nested.
javascript
/* Wrong usage: revalidate outside fetch options */ const res = await fetch('https://api.example.com/data', { revalidate: 10 // ❌ This does nothing }); /* Correct usage: nested inside next */ const res = await fetch('https://api.example.com/data', { next: { revalidate: 10 } // ✅ Works as expected });
Quick Reference
| Option | Description | Example |
|---|---|---|
| next.revalidate | Seconds after which Next.js re-fetches data | next: { revalidate: 60 } |
| Placement | Inside fetch options object | fetch(url, { next: { revalidate: 10 } }) |
| Effect | Enables Incremental Static Regeneration | Refreshes cached data automatically |
| Invalid values | 0 or negative disables caching | Avoid using 0 or negative numbers |
Key Takeaways
Use next: { revalidate: seconds } inside fetch options to control data caching in Next.js.
The revalidate value sets how often Next.js refreshes cached data in seconds.
Place the revalidate option correctly inside the fetch options object under next.
This feature works only in server components or API routes, not in client components.
Avoid zero or negative revalidate values as they disable caching and revalidation.