Data Fetching: Incremental Static Regeneration (ISR) | Next.js (2024)

Examples

Incremental Static Regeneration (ISR) enables you to:

  • Update static content without rebuilding the entire site
  • Reduce server load by serving prerendered, static pages for most requests
  • Ensure proper cache-control headers are automatically added to pages
  • Handle large amounts of content pages without long next build times

Here's a minimal example:

interface Post { id: string title: string content: string} // Next.js will invalidate the cache when a// request comes in, at most once every 60 seconds.export const revalidate = 60 // We'll prerender only the params from `generateStaticParams` at build time.// If a request comes in for a path that hasn't been generated,// Next.js will server-render the page on-demand.export const dynamicParams = true // or false, to 404 on unknown paths export async function generateStaticParams() { let posts: Post[] = await fetch('https://api.vercel.app/blog').then((res) => res.json() ) return posts.map((post) => ({ id: post.id, }))} export default async function Page({ params }: { params: { id: string } }) { let post = await fetch(`https://api.vercel.app/blog/${params.id}`).then( (res) => res.json() ) return ( <main> <h1>{post.title}</h1> <p>{post.content}</p> </main> )}

Here's how this example works:

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

Reference

Route segment config

  • revalidate
  • dynamicParams

Functions

  • revalidatePath
  • revalidateTag

Examples

Time-based revalidation

This fetches and displays a list of blog posts on /blog. After an hour, the cache for this page is invalidated on the next visit to the page. Then, in the background, a new version of the page is generated with the latest blog posts.

export const revalidate = 3600 // invalidate every hour export default async function Page() { let data = await fetch('https://api.vercel.app/blog') let posts = await data.json() return ( <main> <h1>Blog Posts</h1> <ul> {posts.map((post) => ( <li key={post.id}>{post.title}</li> ))} </ul> </main> )}

We recommend setting a high revalidation time. For instance, 1 hour instead of 1 second. If you need more precision, consider using on-demand revalidation. If you need real-time data, consider switching to dynamic rendering.

On-demand revalidation with revalidatePath

For a more precise method of revalidation, invalidate pages on-demand with the revalidatePath function.

For example, this Server Action would get called after adding a new post. Regardless of how you retrieve your data in your Server Component, either using fetch or connecting to a database, this will clear the cache for the entire route and allow the Server Component to fetch fresh data.

'use server' import { revalidatePath } from 'next/cache' export async function createPost() { // Invalidate the /posts route in the cache revalidatePath('/posts')}

View a demo and explore the source code.

On-demand revalidation with revalidateTag

For most use cases, prefer revalidating entire paths. If you need more granular control, you can use the revalidateTag function. For example, you can tag individual fetch calls:

export default async function Page() { let data = await fetch('https://api.vercel.app/blog', { next: { tags: ['posts'] }, }) let posts = await data.json() // ...}

If you are using an ORM or connecting to a database, you can use unstable_cache:

import { unstable_cache } from 'next/cache'import { db, posts } from '@/lib/db' const getCachedPosts = unstable_cache( async () => { return await db.select().from(posts) }, ['posts'], { revalidate: 3600, tags: ['posts'] }) export default async function Page() { let posts = getCachedPosts() // ...}

You can then use revalidateTag in a Server Actions or Route Handler:

'use server' import { revalidateTag } from 'next/cache' export async function createPost() { // Invalidate all data tagged with 'posts' in the cache revalidateTag('posts')}

Handling uncaught exceptions

If an error is thrown while attempting to revalidate data, the last successfully generated data will continue to be served from the cache. On the next subsequent request, Next.js will retry revalidating the data. Learn more about error handling.

Customizing the cache location

Caching and revalidating pages (with Incremental Static Regeneration) use the same shared cache. When deploying to Vercel, the ISR cache is automatically persisted to durable storage.

When self-hosting, the ISR cache is stored to the filesystem (on disk) on your Next.js server. This works automatically when self-hosting using both the Pages and App Router.

You can configure the Next.js cache location if you want to persist cached pages and data to durable storage, or share the cache across multiple containers or instances of your Next.js application. Learn more.

Troubleshooting

Debugging cached data in local development

If you are using the fetch API, you can add additional logging to understand which requests are cached or uncached. Learn more about the logging option.

next.config.js

module.exports = { logging: { fetches: { fullUrl: true, }, },}

Verifying correct production behavior

To verify your pages are cached and revalidated correctly in production, you can test locally by running next build and then next start to run the production Next.js server.

This will allow you to test ISR behavior as it would work in a production environment. For further debugging, add the following environment variable to your .env file:

.env

NEXT_PRIVATE_DEBUG_CACHE=1

This will make the Next.js server console log ISR cache hits and misses. You can inspect the output to see which pages are generated during next build, as well as how pages are updated as paths are accessed on-demand.

Caveats

  • ISR is only supported when using the Node.js runtime (default).
  • ISR is not supported when creating a Static Export.
  • If you have multiple fetch requests in a statically rendered route, and each has a different revalidate frequency, the lowest time will be used for ISR. However, those revalidate frequencies will still be respected by the Data Cache.
  • If any of the fetch requests used on a route have a revalidate time of 0, or an explicit no-store, the route will be dynamically rendered.
  • Middleware won't be executed for on-demand ISR requests, meaning any path rewrites or logic in Middleware will not be applied. Ensure you are revalidating the exact path. For example, /post/1 instead of a rewritten /post-1.

Version history

VersionChanges
v14.1.0Custom cacheHandler is stable.
v13.0.0App Router is introduced.
v12.2.0Pages Router: On-Demand ISR is stable
v12.0.0Pages Router: Bot-aware ISR fallback added.
v9.5.0Pages Router: Stable ISR introduced.
Data Fetching: Incremental Static Regeneration (ISR) | Next.js (2024)

References

Top Articles
Roadmap and polls - Summertime Saga Wiki
The 10 Best Games Like Summertime Saga
Condogames Xyz Discord
Forest Lake Dr
Chokenigg*s
Whiskeytown Camera
Christine Paduch Howell Nj
Westcare Clinic Renton
Lesson 5 Homework 4.5 Answer Key
Ark Rag Desert Drops
Waifu Fighter F95
Mycoverageinfo Pennymac
Kiddle Encyclopedia
205-293-6392
Joy Studio Yupoo
Craigslist Free Stuff North Jersey
Vistaprint Search Engine Listings Manager Review
Fed meeting recap: Chair Jerome Powell defends central bank's decision to go big with first cut
공지/공고 - 10 Things That Your Family Teach You About Triple Bunk Bed With Mattresses
Play Billiards Near Me
Vca Woofapp
866-392-8015
Ksl Classifieds Dirt Bikes
18002226885
Plarium Trick Or Treat
Cuisinart Cbc-7200Pc Manual
La Monja 2 Pelicula Completa Tokyvideo
Deleon Malik Taylor-Griffin
Https://Www.valottery.com/
Emerson Naturals Kratom
What Is The Best Center Build In 2K23
Top 10 SEO Copywriting Service PowerPoint Presentation Templates in 2024
Ric Flair's Net Worth (Updated 2023) | Inspirationfeed
Jellyshroom Caves
Craigslist Hunting Land For Lease In Ga
Warfare Personified Crossword Clue
Tayyy_Boo
Kaiser Hesperia Laboratory Hours
Lifetalent Healthstream Lifepoint
Spc Veterinary Technology Center
Restored Republic December 1 2022
What Is Better Ice Or Sand Blox Fruits
Chuze Fitness Tucson Az Ajo
Livvy Dunne Leaked: Everything You Need to Know - Women The Magazine
Noaa Weather Forecast Pittsburgh
Louise Ogborn Spanking
Eve Fastest Ship
Huron County Jail, OH Inmate Search: Roster & Mugshots
Does Groupme Notify Screenshots
Rise Menu Dispensary
Www.pfmlogin.com Driver Center Login
Latest Posts
Article information

Author: Kerri Lueilwitz

Last Updated:

Views: 6354

Rating: 4.7 / 5 (67 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Kerri Lueilwitz

Birthday: 1992-10-31

Address: Suite 878 3699 Chantelle Roads, Colebury, NC 68599

Phone: +6111989609516

Job: Chief Farming Manager

Hobby: Mycology, Stone skipping, Dowsing, Whittling, Taxidermy, Sand art, Roller skating

Introduction: My name is Kerri Lueilwitz, I am a courageous, gentle, quaint, thankful, outstanding, brave, vast person who loves writing and wants to share my knowledge and understanding with you.