Incremental Static Regeneration

Examples

Version History

VersionChanges
v12.2.0On-Demand ISR is stable
v12.1.0On-Demand ISR added (beta).
v12.0.0Bot-aware ISR fallback added.
v9.5.0Base Path added.

Next.js allows you to create or update static pages after you’ve built your site. Incremental Static Regeneration (ISR) enables you to use static-generation on a per-page basis, without needing to rebuild the entire site. With ISR, you can retain the benefits of static while scaling to millions of pages.

To use ISR, add the revalidate prop to getStaticProps:

  1. function Blog({ posts }) {
  2. return (
  3. <ul>
  4. {posts.map((post) => (
  5. <li key={post.id}>{post.title}</li>
  6. ))}
  7. </ul>
  8. )
  9. }
  10. // This function gets called at build time on server-side.
  11. // It may be called again, on a serverless function, if
  12. // revalidation is enabled and a new request comes in
  13. export async function getStaticProps() {
  14. const res = await fetch('https://.../posts')
  15. const posts = await res.json()
  16. return {
  17. props: {
  18. posts,
  19. },
  20. // Next.js will attempt to re-generate the page:
  21. // - When a request comes in
  22. // - At most once every 10 seconds
  23. revalidate: 10, // In seconds
  24. }
  25. }
  26. // This function gets called at build time on server-side.
  27. // It may be called again, on a serverless function, if
  28. // the path has not been generated.
  29. export async function getStaticPaths() {
  30. const res = await fetch('https://.../posts')
  31. const posts = await res.json()
  32. // Get the paths we want to pre-render based on posts
  33. const paths = posts.map((post) => ({
  34. params: { id: post.id },
  35. }))
  36. // We'll pre-render only these paths at build time.
  37. // { fallback: blocking } will server-render pages
  38. // on-demand if the path doesn't exist.
  39. return { paths, fallback: 'blocking' }
  40. }
  41. export default Blog

When a request is made to a page that was pre-rendered at build time, it will initially show the cached page.

  • Any requests to the page after the initial request and before 10 seconds are also cached and instantaneous.
  • After the 10-second window, the next request will still show the cached (stale) page
  • Next.js triggers a regeneration of the page in the background.
  • Once the page generates successfully, Next.js will invalidate the cache and show the updated page. If the background regeneration fails, the old page would still be unaltered.

When a request is made to a path that hasn’t been generated, Next.js will server-render the page on the first request. Future requests will serve the static file from the cache. ISR on Vercel persists the cache globally and handles rollbacks.

Note: Check if your upstream data provider has caching enabled by default. You might need to disable (e.g. useCdn: false), otherwise a revalidation won’t be able to pull fresh data to update the ISR cache. Caching can occur at a CDN (for an endpoint being requested) when it returns the Cache-Control header.

On-demand Revalidation

If you set a revalidate time of 60, all visitors will see the same generated version of your site for one minute. The only way to invalidate the cache is from someone visiting that page after the minute has passed.

Starting with v12.2.0, Next.js supports On-Demand Incremental Static Regeneration to manually purge the Next.js cache for a specific page. This makes it easier to update your site when:

  • Content from your headless CMS is created or updated
  • Ecommerce metadata changes (price, description, category, reviews, etc.)

Inside getStaticProps, you do not need to specify revalidate to use on-demand revalidation. If revalidate is omitted, Next.js will use the default value of false (no revalidation) and only revalidate the page on-demand when revalidate() is called.

Note: Middleware won’t be executed for On-Demand ISR requests. Instead, call revalidate() on the exact path that you want revalidated. For example, if you have pages/blog/[slug].js and a rewrite from /post-1 -> /blog/post-1, you would need to call res.revalidate('/blog/post-1').

Using On-Demand Revalidation

First, create a secret token only known by your Next.js app. This secret will be used to prevent unauthorized access to the revalidation API Route. You can access the route (either manually or with a webhook) with the following URL structure:

  1. https://<your-site.com>/api/revalidate?secret=<token>

Next, add the secret as an Environment Variable to your application. Finally, create the revalidation API Route:

  1. // pages/api/revalidate.js
  2. export default async function handler(req, res) {
  3. // Check for secret to confirm this is a valid request
  4. if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
  5. return res.status(401).json({ message: 'Invalid token' })
  6. }
  7. try {
  8. // this should be the actual path not a rewritten path
  9. // e.g. for "/blog/[slug]" this should be "/blog/post-1"
  10. await res.revalidate('/path-to-revalidate')
  11. return res.json({ revalidated: true })
  12. } catch (err) {
  13. // If there was an error, Next.js will continue
  14. // to show the last successfully generated page
  15. return res.status(500).send('Error revalidating')
  16. }
  17. }

View our demo to see on-demand revalidation in action and provide feedback.

Testing on-Demand ISR during development

When running locally with next dev, getStaticProps is invoked on every request. To verify your on-demand ISR configuration is correct, you will need to create a production build and start the production server:

  1. $ next build
  2. $ next start

Then, you can confirm that static pages have successfully revalidated.

Error handling and revalidation

If there is an error inside getStaticProps when handling background regeneration, or you manually throw an error, the last successfully generated page will continue to show. On the next subsequent request, Next.js will retry calling getStaticProps.

  1. export async function getStaticProps() {
  2. // If this request throws an uncaught error, Next.js will
  3. // not invalidate the currently shown page and
  4. // retry getStaticProps on the next request.
  5. const res = await fetch('https://.../posts')
  6. const posts = await res.json()
  7. if (!res.ok) {
  8. // If there is a server error, you might want to
  9. // throw an error instead of returning so that the cache is not updated
  10. // until the next successful request.
  11. throw new Error(`Failed to fetch posts, received status ${res.status}`)
  12. }
  13. // If the request was successful, return the posts
  14. // and revalidate every 10 seconds.
  15. return {
  16. props: {
  17. posts,
  18. },
  19. revalidate: 10,
  20. }
  21. }

Self-hosting ISR

Incremental Static Regeneration (ISR) works on self-hosted Next.js sites out of the box when you use next start.

You can use this approach when deploying to container orchestrators such as Kubernetes or HashiCorp Nomad. By default, generated assets will be stored in-memory on each pod. This means that each pod will have its own copy of the static files. Stale data may be shown until that specific pod is hit by a request.

To ensure consistency across all pods, you can disable in-memory caching. This will inform the Next.js server to only leverage assets generated by ISR in the file system.

You can use a shared network mount in your Kubernetes pods (or similar setup) to reuse the same file-system cache between different containers. By sharing the same mount, the .next folder which contains the next/image cache will also be shared and re-used.

To disable in-memory caching, set isrMemoryCacheSize to 0 in your next.config.js file:

  1. module.exports = {
  2. experimental: {
  3. // Defaults to 50MB
  4. isrMemoryCacheSize: 0,
  5. },
  6. }

Note: You might need to consider a race condition between multiple pods trying to update the cache at the same time, depending on how your shared mount is configured.

For more information on what to do next, we recommend the following sections:

Dynamic routingLearn more about dynamic routing in Next.js with getStaticPaths.