Lesson 14 of 15 · 4 min

Incremental Static Regeneration (ISR) in Next.js

Keep static Next.js pages fresh without rebuilding the whole site: time-based revalidation, on-demand revalidation, fallback pages and how ISR works…

On this page
  1. Introduction:
  2. 1. How ISR Works:
  3. 2. ISR in the Pages Router:
  4. 3. ISR with Dynamic Routes:
  5. 4. ISR in the App Router:
  6. 5. On-Demand Revalidation:
  7. 6. Choosing a Revalidation Time:
  8. Conclusion:

Introduction:

In the earlier lessons we met two ways to render a page. Static Site Generation (SSG) builds the HTML once at build time, so pages are extremely fast but can go out of date. Server-Side Rendering (SSR) builds the HTML on every request, so it is always fresh but slower and more expensive.

Incremental Static Regeneration (ISR) gives you the best of both. Pages are generated statically, served from the cache at full speed, and then quietly regenerated in the background after a time you choose, or whenever you tell Next.js the data has changed. You do not need to rebuild and redeploy the whole site to update one blog post.

1. How ISR Works:

Imagine a page with a revalidation time of 60 seconds:

  • The first visitor gets the page that was generated at build time.
  • For the next 60 seconds, every visitor gets that same cached page instantly.
  • After 60 seconds, the next visitor still gets the cached (slightly old) page, but Next.js starts regenerating the page in the background.
  • When regeneration succeeds, the new page replaces the old one in the cache, and everyone after that sees the fresh version.
  • If regeneration fails (for example, the API is down), the old page keeps being served. Your visitors never see an error because of it.

This pattern is called stale-while-revalidate: serve the stale copy now, revalidate in the background.

2. ISR in the Pages Router:

Add a revalidate property to the object returned by getStaticProps. The value is the number of seconds after which the page may be regenerated.

// pages/products.js
export async function getStaticProps() {
  const res = await fetch("https://dummyjson.com/products?limit=10");
  const data = await res.json();

  return {
    props: { products: data.products },
    revalidate: 60, // regenerate at most once every 60 seconds
  };
}

export default function Products({ products }) {
  return (
    <ul>
      {products.map((product) => (
        <li key={product.id}>
          {product.title} - ${product.price}
        </li>
      ))}
    </ul>
  );
}

That single line is all it takes to turn a static page into an ISR page.

3. ISR with Dynamic Routes:

ISR becomes really powerful with dynamic pages like /products/[id]. You can pre-build only your most popular pages and let Next.js generate the rest the first time someone visits them.

// pages/products/[id].js
export async function getStaticPaths() {
  // Pre-render only the first 5 products at build time
  const res = await fetch("https://dummyjson.com/products?limit=5");
  const data = await res.json();

  return {
    paths: data.products.map((p) => ({ params: { id: String(p.id) } })),
    fallback: "blocking",
  };
}

export async function getStaticProps({ params }) {
  const res = await fetch(`https://dummyjson.com/products/${params.id}`);

  if (!res.ok) {
    return { notFound: true, revalidate: 60 };
  }

  const product = await res.json();
  return { props: { product }, revalidate: 300 };
}

export default function Product({ product }) {
  return (
    <article>
      <h1>{product.title}</h1>
      <p>{product.description}</p>
      <strong>${product.price}</strong>
    </article>
  );
}

The fallback option decides what happens for a path that was not built ahead of time:

  • fallback: false – unknown paths return a 404 page.
  • fallback: "blocking" – the server generates the page on the first request and the visitor waits for it, just like SSR. After that it is cached like any other static page.
  • fallback: true – the visitor immediately gets a loading version of the page (check router.isFallback), and the real content appears when it is ready.

4. ISR in the App Router:

In the app router you set the revalidation time with a route segment config export, or per request on fetch:

// app/products/page.js
export const revalidate = 60; // seconds

export default async function ProductsPage() {
  const res = await fetch("https://dummyjson.com/products?limit=10");
  const data = await res.json();

  return (
    <ul>
      {data.products.map((product) => (
        <li key={product.id}>{product.title}</li>
      ))}
    </ul>
  );
}
// Revalidate only this request, every 5 minutes
const res = await fetch("https://dummyjson.com/products", {
  next: { revalidate: 300 },
});

For dynamic routes, generateStaticParams plays the role of getStaticPaths:

// app/products/[id]/page.js
export const revalidate = 300;

export async function generateStaticParams() {
  const res = await fetch("https://dummyjson.com/products?limit=5");
  const data = await res.json();
  return data.products.map((p) => ({ id: String(p.id) }));
}

export default async function ProductPage({ params }) {
  const { id } = await params;
  const res = await fetch(`https://dummyjson.com/products/${id}`);
  const product = await res.json();
  return <h1>{product.title}</h1>;
}

5. On-Demand Revalidation:

Waiting for a timer is fine for many pages, but sometimes you want an update to appear right away, for example the moment an editor publishes a post in a CMS. On-demand revalidation lets you clear a page from the cache whenever you like, usually from an API route that your CMS calls through a webhook.

// pages/api/revalidate.js
export default async function handler(req, res) {
  // Protect the endpoint with a secret token
  if (req.query.secret !== process.env.REVALIDATE_SECRET) {
    return res.status(401).json({ message: "Invalid token" });
  }

  try {
    await res.revalidate(`/products/${req.query.id}`);
    return res.json({ revalidated: true });
  } catch (err) {
    return res.status(500).send("Error revalidating");
  }
}

In the app router, use revalidatePath (or revalidateTag if you tagged your fetches):

// app/api/revalidate/route.js
import { revalidatePath } from "next/cache";

export async function POST(request) {
  const { secret, path } = await request.json();

  if (secret !== process.env.REVALIDATE_SECRET) {
    return Response.json({ message: "Invalid token" }, { status: 401 });
  }

  revalidatePath(path);
  return Response.json({ revalidated: true, path });
}

Now your CMS can call /api/revalidate after every save, and the updated page is regenerated on the next visit.

6. Choosing a Revalidation Time:

  • Blog posts and docs: a few minutes to an hour, plus on-demand revalidation when you publish.
  • Product listings and prices: 30 to 60 seconds.
  • Data that must be correct on every request (a shopping cart, a user’s dashboard): do not use ISR, use server-side rendering or client-side fetching instead.

Tip: ISR does not run during npm run dev. In development every request regenerates the page. To see ISR in action, run npm run build and then npm start.

Conclusion:

Incremental Static Regeneration lets you keep the speed of static pages while still showing fresh data. You learned how the stale-while-revalidate cycle works, how to add revalidate in getStaticProps and in the app router, how fallback handles pages that were not pre-built, and how to update a page instantly with on-demand revalidation. In the next lesson we will learn about middleware, which runs code before a request reaches your pages.

More from Next.js Tutorial