The Hybrid Approach: ISR and Revalidation
Explore how Next.js enables fast static page delivery with Incremental Static Regeneration (ISR) using stale-while-revalidate caching. Learn to configure time-based revalidation and set up on-demand revalidation with tagged caching and route handlers. Understand when to use ISR to balance performance with data freshness in applications like blogs, e-commerce, and marketing pages.
So far, we’ve seen two main rendering strategies: dynamic (SSR) and static (SSG). But what about pages that are mostly static but still need periodic updates, like a blog post that receives a correction or an e-commerce product whose price changes?
For this, Next.js offers a powerful hybrid approach: Incremental Static Regeneration (ISR). This lets us keep the performance of a static site while gracefully updating its content after deployment.
From static to stale-while-revalidate
ISR introduces a more intelligent caching strategy known as stale-while-revalidate which works as follows:
On the first request, the page is generated and served to the user, after which it’s cached for future requests.
Subsequent requests are served the “stale” (cached) page instantly.
If a request comes in after a specified “revalidation” period has passed, Next.js serves the stale content while regenerating the page in the background with fresh data.
Once the regeneration is complete, the cache is updated with the new page. Future visitors will now receive the updated version.
This approach gives us the best of both worlds: users always get a fast, static response, while the content is automatically and incrementally updated in the background.
Implementing time-based revalidation
In modern Next.js, we enable time-based ISR by telling our fetch requests how often they should revalidate their cache. Next.js extends the native fetch API, allowing us to pass a configuration object called next.
To do this, we add a revalidate property to the next object in our fetch call. The value is the number of seconds after which the data should be considered “stale” and a revalidation should be ...