Revalidating data in Next.js is a crucial process that ensures your application always serves up-to-date content. Revalidation clears the data cache and re-fetches the latest data, either at timed intervals or based on specific events.
Time-based revalidation occurs automatically after a specified time interval, which is particularly useful for data that changes infrequently or for cases where data freshness isn't critical.
next.revalidate with fetchYou can specify the cache lifetime for a resource (in seconds) using the next.revalidate option with the fetch API:
fetch('https://...', { next: { revalidate: 3600 } }); // Revalidate every hour
revalidate in a Layout or Page ComponentYou can set the revalidation interval globally for a segment by defining the revalidate export in a layout or page file:
// layout.js or page.js
export const revalidate = 3600; // Revalidate at most every hour
fetch requests with varying revalidation intervals exist in a static segment, the shortest interval will be used for all requests.fetch request is revalidated independently.On-demand revalidation allows you to revalidate data based on specific events, such as form submissions or data updates. This ensures the latest data is shown as soon as possible.
revalidatePath.revalidateTag.fetch