Published on

Understanding ISR in Next.js

Authors
  • avatar
    Name
    David Rhodes
    Twitter
hourglass as metaphor for performance

Next.js is a popular React framework that provides various rendering approaches to create fast and performant web applications. One of the key features of Next.js is Static Site Generation (SSG), which allows you to pre-build and serve static pages that can be hosted on a Content Delivery Network (CDN) for fast delivery to users.

However, static site generation has limitations, such as the inability to handle real-time data or dynamic content. That's where Incremental Static Regeneration (ISR) comes in. ISR allows you to regenerate specific pages or parts of pages on-demand, while still benefiting from the performance benefits of static site generation.

What is Incremental Static Regeneration?

Incremental Static Regeneration (ISR) is a feature in Next.js that enables you to generate static pages on-demand at runtime. In traditional static site generation, all pages are pre-generated at build time, resulting in a complete set of HTML files. However, this can be limiting in scenarios where the data changes frequently or where there are a large number of pages that need to be pre-generated.

With ISR, Next.js can pre-build only the essential parts of the site at build time, such as the navigation and layout, and leave the dynamic content to be generated on-demand at runtime. When a request is made for a specific page, the server generates the content for that page on-the-fly using data fetched from APIs or databases.

Use Cases of Incremental Static Regeneration

ISR can be useful in a variety of scenarios in a Next.js site. Here are a few:

  • E-commerce: In an e-commerce website, products and prices can change frequently. With ISR, you can pre-generate the product catalog and other static parts of the site, while still allowing the dynamic parts like product availability and pricing to be generated on-the-fly at runtime.

  • Large Sites: In a large website with a lot of pages, pre-generating all the pages at build time may not be practical. ISR pre-generates only the essential parts of the site, such as the navigation and layout, and leave the dynamic content to be generated on-demand at runtime.

  • News: In a news website, articles can be published frequently, and readers expect to see the latest news as soon as it is available. Using ISR, you can pre-generate the static parts of the site and use server-side rendering to generate the latest articles on-the-fly at runtime.

Where Incremental Static Regeneration Falls in the Next.js Rendering Approaches

ISR is specific to the Static Site Generation (SSG) rendering mode in Next.js. In SSG mode, all pages of a website are pre-rendered as static HTML files at build time. This approach provides fast and efficient performance, as the static files can be served quickly from a Content Delivery Network (CDN) or web server.

In contrast, the other two rendering modes in Next.js, Server-side Rendering (SSR) and Client-side Rendering (CSR), do not use Incremental Static Regeneration. In SSR mode, pages are generated on-the-fly on the server in response to client requests. In CSR mode, the entire application is generated on the client-side using JavaScript.

How to Implement ISR

Define getStaticProps function in your Next.js project's page component. This function should fetch the data that you want to statically generate and return it as props.

Set the revalidate option in the getStaticProps return object. This option determines how often Next.js will regenerate the page on the server-side. For ISR, you should set this value to the number of seconds you want to wait before regenerating the page -- here, the page will be regenerated every 60 seconds. Latin phrases (this open API) may not be updated every minute, but imagine a news feed, or a CRM sales results countdown at the end of the quarter.

Note the Next.js documentation includes the getStaticPaths function, but it's not necessary for our use case because we aren't using dynamic routes.

export async function getStaticProps() {
 // Fetch data from an API or database
 const res = await fetch('https://jsonplaceholder.typicode.com/posts');
 const data = await res.json();

 // Pass data as props to the page component
 return {
   props: { data },
   revalidate: 60, // Revalidate every 60 seconds
 };
}

So your final page should look like this:

import Head from 'next/head';
import styles from '../styles/Home.module.css';

export async function getStaticProps() {
  // Fetch data from an API or database
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');
  const data = await res.json();

  // Pass data as props to the page component and stream any updates
  return {
    props: { data },
    revalidate: 60, // Revalidate every 60 seconds
  };
}

export default function Home({ data }) {
  return (
    <div className={styles.container}>
      <Head>
        <title>getStaticProps</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <ul>
          {data.map((item) => (
            <li key={item.id}>{item.title}</li>
          ))}
        </ul>
      </main>
    </div>
  );
}

Summary

Incremental Static Regeneration is a powerful feature of Next.js that allows you to generate static pages on-demand at runtime while still benefiting from the performance benefits of static site generation. ISR can be useful in a variety of scenarios, such as e-commerce websites, large websites, and news websites.

When it comes to rendering approaches in Next.js, ISR is specific to the Static Site Generation (SSG) mode. In contrast, Server-side Rendering (SSR) and Client-side Rendering (CSR) do not use ISR.

The concept of generating static pages on-demand at runtime has been around for a while, and other frameworks such as Gatsby and Hugo have also implemented similar functionality. For example, Gatsby offers a feature called "Incremental Builds," which allows you to build and deploy only the pages that have changed since the last build, rather than rebuilding the entire site from scratch. Similarly, Hugo offers a feature called "Fast Render Mode," which generates static pages on-demand at runtime for pages that have been updated since the last build.

So whether you're building a small website or a large application, understanding the different rendering approaches and features available can help you create fast and performant web applications that meet the needs of your users. By leveraging Incremental Static Regeneration and other features, you can provide a great user experience while still maintaining the speed and performance that users expect from modern web applications.

Deployed on Netlify

GitHub Repo