Data Fetching with Incremental Static Regeneration (ISR) in Next.js

Development

17/12/2024

incremental-static-regeneration

I. What is Incremental Static Regeneration (ISR)?

Incremental Static Regeneration (ISR) enables developers and content editors 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. Static pages can be generated at runtime (on-demand) instead of at build-time with ISR. Using analytics, A/B testing, or other metrics, you are equipped with the flexibility to make your own tradeoff on build times.

For instance, an e-commerce website with 100,000 products can leverage ISR for:

  • Faster Builds: Generate the most popular 1,000 products at build-time. Requests made to other products will be a cache miss and statically generate on-demand: 1-minute builds.
  • Higher Cache Hit Rate: Generate 10,000 products at build-time, ensuring more products are cached ahead of a user’s request: 8-minute builds.
incremental-static-regeneration

II. Data Fetching

Next.js uses a combination of static generation and server-side regeneration to implement ISR. When a user requests a page:

  • If the page exists in the cache and hasn’t exceeded the revalidation time, the static page is served.
  • If the revalidation time has passed, a new version of the page is fetched and generated in the background.
  • Subsequent users will see the newly updated page after it has been regenerated.
incremental-static-regeneration

1. Next.js can define a revalidation time per page. Let’s set it at 60 seconds.

2. The initial request to the product page will show the cached page with the original price.

3. The data for the product is updated in the CMS.

4. Any requests to the page after the initial request and before 60 seconds are cached and instantaneous.

5. After the 60-second window, the next request will still show the cached (stale) page. Next.js triggers a regeneration of the page in the background.

6. Once the page has been successfully generated, Next.js will invalidate the cache and show the updated product page. If the background regeneration fails, the old page remains unaltered.

III. Implementing ISR in Next.js

1. For Page Router:

The Page Router was the default in Next.js until version 13 introduced the App Router. In this router, ISR is implemented by using the getStaticProps function within a page component.

incremental-static-regenerationincremental-static-regenerationincremental-static-regeneration

Key Points:

  • getStaticProps: Fetches the data for the page. By returning a revalidate key, Next.js regenerates the page in the background every 10 seconds.
  • getStaticPaths: Tells Next.js which pages to statically generate at build time. The fallback: 'blocking' option ensures that if a user requests a page that isn’t generated yet, it will be rendered on demand.

2. For App Router(Next.js recommend using App router): 

Next.js 13 introduced the App Router, which is a new way of defining routes and data fetching. The App Router uses React Server Components (RSC) and provides better flexibility and ergonomics. With the App Router, Incremental Static Regeneration is implemented using the fetch function with caching options.

incremental-static-regenerationincremental-static-regeneration

Key Points:

  • generateStaticParams: Pre-generates static parameters for the route (similar to getStaticPaths). It helps Next.js know which pages to statically generate at build time.
  • fetch with next.revalidate: This is where ISR happens in the App Router. The revalidate option in fetch tells Next.js to revalidate the data and regenerate the static page every 60 seconds.

3. How the above 2 code snippets work:

  • During the next build, all known blog posts are generated (there are 1000 product).
  • All requests made to these pages (e.g. /blog/1) are cached and instantaneous.
  • After 60 seconds has passed, the next request will still show the cached (stale) page.
  • The cache is invalidated and a new version of the page begins generating in the background.
  • Once generated successfully, Next.js will display and cache the updated page.
  • If /blog/1001 is requested, Next.js will generate and cache this page on-demand.

IV. When Should You Use ISR?

ISR is ideal for scenarios where you need up-to-date content but don’t require real-time data.

Key Use Cases:

  • Content with Periodic Updates: Blogs, e-commerce product pages, or marketing sites.
  • SEO Optimization: Freshly updated content improves search rankings.

Efficient Updates: Avoid full site rebuilds for specific content changes.

V. When Not to Use ISR

  • Applications Requiring Real-Time Updates: For scenarios where real-time data updates are crucial—such as live sports scores, chat apps, or stock trading platforms—ISR may not be the most suitable option. Instead, server-side rendering (SSR) or client-side data fetching is recommended to ensure up-to-the-second accuracy.
  • Rapidly Changing Data: When your website’s data is highly dynamic and updates occur every second, like stock prices or cryptocurrency rates, ISR’s fixed revalidation intervals might fall short. In such cases, SSR or client-side fetching is a more effective solution.

VI. Conclusion

Incremental Static Regeneration is a powerful tool when you need a balance between static performance and dynamic updates. It is best used when your content changes on a regular, but not real-time, basis. Whether you're building product pages, blogs, or large-scale content sites, ISR allows you to keep your pages fresh and responsive without sacrificing performance or scalability. Use ISR when you want to give your users fast, static pages with the confidence that content will be up-to-date in the background.

Featured posts

ss-white-paper-thumbnail

Agile Testing in Scrum: Methods and Best Practices

Agile Testing plays a pivotal role in Agile software development, ensuring that testing aligns with the dynamic, iterative, and collaborative nature of this methodology. This article explores Agile Testing within the context of Scrum, delving into its core principles, the Agile Testing Quadrants, and various methods such as Behavior-Driven Development (BDD), Acceptance Test-Driven Development (ATDD), and exploratory testing. By understanding these concepts, organizations can enhance the quality and efficiency of their software development processes while delivering products that align closely with customer needs.

Development

20/12/2024

ss-white-paper-thumbnail

Overview about Craft.js - library used for page builder

Building rich, customizable user interfaces is a challenge that many web applications face. Developers need solutions that provide flexibility, performance, and extensibility, especially for drag-and-drop editors, landing page builders, and WYSIWYG content creation. Enter Craft.js, a headless framework for building these complex user interfaces with React. In this guide, we will learn about the architecture of Craft.js, the workflows, custom components, state management, and extensibility.

Development

13/12/2024

Quyet

Related contents

ss-white-paper-thumbnail
Development
Overview about Craft.js - library used for page builder

Building rich, customizable user interfaces is a challenge that many web applications face. Developers need solutions that provide flexibility, performance, and extensibility, especially for drag-and-drop editors, landing page builders, and WYSIWYG content creation. Enter Craft.js, a headless framework for building these complex user interfaces with React. In this guide, we will learn about the architecture of Craft.js, the workflows, custom components, state management, and extensibility.

13/12/2024

Quyet