Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 72 ยท Data Fetching and Caching

Revalidating Data

Keep cached Next.js data fresh: time-based revalidation, on-demand revalidatePath and revalidateTag, updateTag for read-your-writes and stale-while-revalidate.

Caching makes pages fast, but cached data goes out of date. A new blog post is published, a price changes, an author fixes a typo. Revalidation is the process of replacing cached data with fresh data. Next.js gives you two families of tools: time-based revalidation, where entries refresh themselves after a set time, and on-demand revalidation, where your code says "this changed, refresh it now".

This lesson covers both. You will see the functions revalidatePath, revalidateTag and updateTag, learn the difference between marking data stale and expiring it immediately, and wire a webhook so that a content system can refresh your site. You should already know the cache layers from Caching in Next.js: the Big Picture and the tags from The use cache Directive and Cache Components.

Real Next.js cannot run on this site, so its code is read-only. The runnable examples are Node.js stand-ins: a tagged cache that behaves like the real functions, and a webhook handler that uses the standard Request and Response objects.

Time-based revalidation

The simplest strategy is to accept that data may be a little old, and refresh it on a schedule. You set that time next to the data. With Cache Components it is the revalidate number in cacheLife; in the classic fetch model it is a revalidate option:

TSX
// Cache Components (real Next.js 16, read-only)
import { cacheLife } from 'next/cache';

export async function getHeadlines() {
  'use cache';
  cacheLife({ stale: 60, revalidate: 300, expire: 3600 });
  const response = await fetch('https://api.example.com/headlines');
  return response.json();
}
TSX
// Classic fetch options (real Next.js, read-only)
await fetch('https://api.example.com/headlines', { next: { revalidate: 300 } });

Both say: "after five minutes this is old". What happens next is stale-while-revalidate: the first visitor after that moment still gets the old copy instantly, and the server fetches a fresh one in the background for everyone who comes later. No visitor waits for the refresh.

sequenceDiagram
  participant V as Visitor
  participant C as Cache
  participant O as Data source
  V->>C: Request (entry is fresh)
  C-->>V: Cached copy
  Note over C: revalidate time passes
  V->>C: Request (entry is old)
  C-->>V: Old copy, no waiting
  C->>O: Refresh in the background
  O-->>C: New data stored
  V->>C: Next request
  C-->>V: New copy

An old entry is still served instantly. The refresh happens in the background and the visitor after next sees the new data.

Time-based revalidation is the right choice when "a few minutes behind" is acceptable: news lists, product catalogs, public dashboards. Its weakness is that it knows nothing about changes. A typo fix can sit unseen until the timer runs out. For that you need on-demand revalidation.

On-demand revalidation

On-demand revalidation lets the code that changes data tell Next.js what to refresh. It runs in two places: a Server Action (covered in Server Actions) that handles a form, or a Route Handler (covered in Route Handlers) that receives a webhook. You can target a path or a tag.

revalidatePath

revalidatePath clears the cached data of a route, so the next visit renders it again:

TSX
// real Next.js, read-only
'use server';
import { revalidatePath } from 'next/cache';

export async function publishPost(formData: FormData) {
  await db.post.create({ data: { title: String(formData.get('title')) } });

  revalidatePath('/blog');                  // the list page
  revalidatePath('/blog/[slug]', 'page');   // every post page (dynamic route pattern)
  revalidatePath('/', 'layout');            // everything under the root layout
}

The second argument says what the path means: a specific page or a layout, which includes everything below it. It is simple, but it is also coarse. The function that changed a post has to know every page that shows posts.

revalidateTag

Tags solve that problem. Cached entries carry labels, and you invalidate by label, not by page. A post list, a sidebar with recent posts and an RSS endpoint can all be tagged posts. One call refreshes them all, and the mutation does not need to know where they are:

TSX
// real Next.js, read-only
import { cacheTag } from 'next/cache';

export async function getPosts() {
  'use cache';
  cacheTag('posts');
  return db.post.findMany();
}
TSX
// real Next.js, read-only
'use server';
import { revalidateTag } from 'next/cache';

export async function publishPost(formData: FormData) {
  await db.post.create({ data: { title: String(formData.get('title')) } });
  revalidateTag('posts', 'max'); // mark everything tagged "posts" as stale
}

In Next.js 16, revalidateTag takes a second argument: a cache-life profile such as 'max'. It means "mark this stale, and refresh it in the background using stale-while-revalidate with that profile". The older single-argument form is deprecated. In the classic model the same tag comes from the fetch option next: { tags: ['posts'] }.

updateTag: read your own writes

Stale-while-revalidate is not always what you want. Imagine a user writes a comment and is redirected to the page. If the page serves the old cached copy once, their own comment is missing, which feels like a bug. updateTag is for this case. It is available only in Server Actions, and it expires the entries immediately, so the next read waits for fresh data:

TSX
// real Next.js, read-only
'use server';
import { updateTag } from 'next/cache';
import { redirect } from 'next/navigation';

export async function addComment(formData: FormData) {
  await db.comment.create({ data: { text: String(formData.get('text')) } });
  updateTag('comments'); // the next request waits for fresh data
  redirect('/thread');   // so this page already shows the new comment
}

Choosing a tool

Time-based Refresh on a timer. No code at change time.
revalidateTag Mark tagged data stale. Visitors never wait.
updateTag Expire at once. The writer sees their change.
revalidatePath Clear one route. Simple but coarse.

Mix them: a timer as a safety net, tags for precision.

1 / 2

There is a fourth function, refresh(), also for Server Actions. It does not touch the cache. It refreshes the uncached parts of the page the user is looking at, such as a notification count. Use it after a change that affects only live data.

When an action uses one of these functions, Next.js also clears the matching parts of the browser's router cache, so the user sees the new data on the page they return to.

A model of tags and the two flavors

The stand-in below builds a small cache with tags and three operations. revalidateTag() marks entries stale: the next read returns the old value, and the cache refreshes it in the background. updateTag() deletes the entries, so the next read has to wait for a new load. The first part of the output shows the problem that revalidation solves, because the database changes and nobody tells the cache.

Read the "via" column. It is the key to the difference: stale, refreshing returns old data at once and miss waits for new data.

Node.js Tags, stale-while-revalidate and updateTag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Step through the output. The first read is a miss and the second a hit. After C is added, the cache still returns A, B: that is the stale-data problem. After revalidateTag, the next read still answers with A, B, but marked stale, refreshing, and the refresh finishes behind it, so the visitor after that sees A, B, C. After adding D and calling updateTag, the very next read is a miss and already contains D. That is the read-your-writes behavior.

Webhooks: refreshing from outside

Content often changes outside your app: an editor publishes in a CMS, a payment provider updates a plan. The CMS can call a Route Handler on your site, which calls revalidateTag. A handler like this is a public endpoint, so it must check a secret before doing anything:

TSX
// app/api/revalidate/route.ts  (real Next.js, read-only)
import { revalidateTag } from 'next/cache';

export async function POST(request: Request) {
  if (request.headers.get('x-webhook-secret') !== process.env.REVALIDATE_SECRET) {
    return Response.json({ error: 'unauthorized' }, { status: 401 });
  }
  const { tag } = await request.json();
  revalidateTag(tag, 'max');
  return Response.json({ revalidated: true, tag });
}

Route Handlers use the standard Request and Response objects, so you can test the logic outside Next.js. The stand-in below does exactly that, with a tiny entry list instead of the real cache. It sends three requests: no secret, a missing tag and a correct one. Notice that the tag posts matches two entries, while an unrelated entry stays fresh.

Node.js A revalidation webhook handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The unauthorized request is rejected with 401 before anything is read. The request with an empty body fails validation with 400. The valid call returns 200 and reports that two entries became stale, and the last line shows team untouched.

Never expose a revalidation endpoint without a secret. Anyone who finds it could force your site to refresh constantly, which defeats the cache and can overload your data source. Compare the secret in constant time in production code, and keep it in an environment variable, as in Keeping Server Code on the Server.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does stale-while-revalidate mean for the first visitor after an entry becomes old?

    The visitor is served instantly from the old entry. The refresh runs behind the scenes, so later visitors get the new data.
  2. 2. A user submits a comment and is redirected to the thread. Which call guarantees they see their comment right away?

    updateTag expires the entries immediately, so the next read waits for fresh data and includes the new comment. revalidateTag would serve the old copy once.
  3. 3. Why prefer tags over revalidatePath for a list of posts shown on many pages?

    The code that changes a post does not need to know every page that displays posts. It invalidates the tag and all labelled entries are refreshed.
  4. 4. Where can updateTag be called?

    updateTag is meant for Server Actions, where a user's own change has to be visible right away. Route Handlers use revalidateTag.
  5. 5. What must a public revalidation webhook do before it calls revalidateTag?

    The endpoint is reachable by anyone who knows the URL. Checking a secret keeps strangers from forcing refreshes.

Summary

  • Revalidation replaces cached data with fresh data, either on a timer (time-based) or when your code says so (on-demand).
  • Time-based refresh uses cacheLife's revalidate (or the classic revalidate fetch option) and follows stale-while-revalidate.
  • revalidateTag(tag, 'max') marks tagged entries stale. Visitors are served the old copy once while the refresh runs.
  • updateTag(tag) expires entries at once, only in Server Actions, so the person who made a change sees it immediately.
  • revalidatePath clears a route and is simple but coarse. Tags are more precise.
  • refresh() refreshes uncached live data and does not touch the cache.
  • Webhooks call Route Handlers that revalidate tags, and they must verify a secret.

Next, see how Next.js decides whether a route is static or dynamic in Static vs Dynamic Rendering.