Topic 41 of 47
Time-Based Cache Revalidation
Overview
Instead of manually invalidating the cache, you can tell Next.js to automatically re-fetch data in the background after a certain amount of time has passed. This is known as Incremental Static Regeneration (ISR).
Syntax
tsx
// In a Server Component or utility file
export default async function WeatherWidget() {
// Re-fetch this data at most once every 3600 seconds (1 hour)
const res = await fetch('https://api.weather.com/current', {
next: { revalidate: 3600 }
});
const data = await res.json();
return <div>Temp: {data.temp}°C</div>;
}Common Pitfalls
- If two separate fetch requests on the same page have different revalidate times, Next.js will use the shortest time for the whole route.
- Time-based revalidation happens in the background. The user who triggers the revalidation (by visiting after the time expires) will still see the old cached data, but the NEXT visitor will see the fresh data.
Real-World Example
Setting a route-level revalidation time for all fetch requests on a page:
example
tsx
// app/blog/page.tsx
// This tells Next.js to revalidate the ENTIRE page every 60 seconds
export const revalidate = 60; // seconds
export default async function Blog() {
// Even if this fetch doesn't specify a revalidate time,
// the route segment config above forces it to 60s
const posts = await db.getLatestPosts();
return (
<ul>
{posts.map(post => <li key={post.id}>{post.title}</li>)}
</ul>
);
}