tezvyn:

Next.js Caching: When and How to Revalidate Data

AI-drafted, machine-checkedSource: nextjs.orgadvanced

Next.js aggressively caches data by default. Revalidation is how you tell it the data is stale, either after a set time or on-demand after a mutation. The footgun is forgetting `fetch` is cached; use `revalidatePath` or `revalidateTag` to bust the cache.

WHY IT EXISTS: Modern web apps need to be both fast and accurate. Serving data from a cache is fast, but the data can become stale. Fetching fresh data for every request is accurate but slow. Caching with revalidation provides a necessary compromise, allowing developers to define rules for when to invalidate and refetch data.

THE MENTAL MODEL: Think of the Next.js data cache as a smart pantry. By default, it stocks an item (a piece of data) and keeps it forever. Revalidation is your instruction list for the pantry. Time-based revalidation is like a note saying, "Toss the milk after 7 days." On-demand revalidation is like pressing a button that says, "We just used the last egg, go buy more now."

HOW IT WORKS: Next.js extends the native fetch API to integrate with its caching system. By default, any data fetched with fetch in a Server Component is cached indefinitely. You control this behavior in two main ways. First, for time-based revalidation, you add an option to your fetch call: fetch('...', { next: { revalidate: 3600 } }) to refetch the data at most once per hour. Second, for on-demand revalidation, you use functions like revalidatePath('/products') or revalidateTag('product-list') inside Server Actions. These are typically called right after a database mutation to invalidate the relevant cached data.

WHEN TO USE IT: Use time-based revalidation for data that updates periodically but doesn't need to be real-time, like a news homepage. Use on-demand revalidation for data that changes as a direct result of user actions, such as updating a profile or posting a comment. This ensures the UI reflects the change on the next page load.

WHEN NOT TO USE IT: Avoid caching for data that must be absolutely real-time and is unique to a user session, like a shopping cart's contents. For these cases, you can explicitly opt out of caching by using fetch('...', { cache: 'no-store' }). Using dynamic functions like cookies() or headers() also opts a route out of static caching.

ONE CANONICAL EXAMPLE: A user submits a form to update their bio. The form calls a Server Action. This action first updates the bio in the database. Immediately after the database write succeeds, the action calls revalidatePath('/profile'). The next time anyone navigates to /profile, Next.js knows its cached version is stale and will fetch the new data, displaying the updated bio.

Read the original → nextjs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.