At the end of the previous lesson you put an event back on its date and the home page still didn't show it. The cache was keeping its side of the deal: nobody had told it something had changed. A cache without notifications is just a delay; with them, you can store things for a long time and still show what's right.

Next.js offers several ways to send that notification, with similar names and different effects: updateTag, revalidateTag, revalidatePath and refresh. They differ in three things: who waits, what's invalidated and what happens in the browser. This lesson tells them apart, explains where each one can be called from and settles what AgendaViva will use for each operation. The operations themselves, with Server Actions and Route Handlers, arrive in modules 6 and 7; here you'll only see the minimum needed to understand and try out the notifications.

  1. What invalidating means

The same piece of data can be stored in three places at once:

flowchart LR
    A["use cache entry<br/>listUpcomingEvents(6)"] --> B["Prerendered page<br/>HTML and RSC Payload for /"]
    B --> C["Router cache<br/>in each browser"]

The page was built with the entry, and it inherits its tags: invalidating events affects both. The browser is another story, because it's outside the server; it has its own section.

Two ideas apply to all the functions in this lesson:

  • Invalidating doesn't regenerate. It marks what's stored as no longer valid. The work is done when a request arrives that needs it. Invalidating a tag present on a thousand pages doesn't trigger a thousand renders.
  • The value isn't updated: it's discarded. The cached function will run again and read the database. That's why the notification always goes after the write.

And the distinction that organizes everything else: marking as stale, which allows serving the old version while the new one is prepared, or as expired, which forces the next request to wait.

  1. updateTag: seeing what you've just done

Someone who saves a form expects to see their change instantly. If they saw the previous version, they'd think it hadn't been saved. This guarantee is called read-your-own-writes, and it's what updateTag provides:

// Example only: Server Actions are explained in 06-01
'use server'

import { updateTag } from 'next/cache'
import { EVENTS_TAG, eventTag } from '@/lib/tags'

export async function changeTitle(slug: string, title: string) {
  // 1. Check permission and validate (modules 6 and 8)
  // 2. Write
  await saveTitle(slug, title)
  // 3. Notify
  updateTag(eventTag(slug))
  updateTag(EVENTS_TAG)
}
  • It expires all entries with that tag. The next request that needs them waits for the new data.
  • It only works in Server Actions. In a Route Handler, or while rendering, it throws an error. That's consistent with its purpose: it makes sense when there's a user waiting for the response to their action.
  • The action's response already brings the updated screen. Next.js rerenders the current route and sends it in the same round trip, whether or not it carries the tag. Whatever isn't cached is read again; whatever is cached without that tag is reused.
  • It clears the router cache in that browser: prefetched routes and those stored for back and forward navigation.

The next visit pays the price, whoever it's from: if the page was in high demand, someone will wait while it's regenerated.

  1. revalidateTag: notifying without hurry

Many changes have nobody waiting on them: a nightly process that imports events, a content management system that reports a publication. Or the person writing isn't the person reading. In that case it's better for nobody to wait:

import { revalidateTag } from 'next/cache'
import { EVENTS_TAG } from '@/lib/tags'

revalidateTag(EVENTS_TAG, 'max')

It marks entries as stale. The first request afterwards receives the old version and starts the renewal; the following ones, as soon as it finishes, get the new one. The second argument is required, and says for how long serving the old version is tolerated:

Second argument Effect
'max' Tolerated for up to a year: in practice, the old version is always served while it's renewed. It's the recommended one
Another profile, predefined or custom The same, with its expire as the limit. Of the three times, only that one is read
{ expire: 60 } The limit, in seconds
{ expire: 0 } Not tolerated: the next request waits. Like updateTag, but also outside Server Actions
None Old, deprecated form: TypeScript rejects it. It was equivalent to { expire: 0 }

A common misreading: revalidateTag(tag, 'hours') does not make the new entry last hours. The lifetime is still set by cacheLife. Here the profile only measures how patient you are with the old version.

// Example only: an endpoint called by another system (07-03)
export async function POST(request: Request) {
  if (!isAuthorizedRequest(request)) {
    return new Response(null, { status: 401 })
  }
  revalidateTag(EVENTS_TAG, 'max')
  return Response.json({ notified: true })
}

It's a POST, even though it receives no body, because it changes something. A GET could be triggered by a crawler, a prefetch or the address bar, and under the rules from 05-01 a GET without request data could even be prerendered. And it has a check: a public endpoint that clears the cache is a cheap way to take down a database.

3.1. The difference, over time

sequenceDiagram
    participant E as Writer
    participant S as Server
    participant V as Another visitor
    Note over E,V: updateTag
    E->>S: Server Action
    S-->>E: current route with the new data
    V->>S: GET /
    Note over S: regenerates while V waits
    S-->>V: new page
    Note over E,V: revalidateTag with 'max'
    E->>S: notification
    S-->>E: done
    V->>S: GET /
    S-->>V: old page, instantly
    Note over S: regenerates in the background
    V->>S: GET /
    S-->>V: new page

With 'max' you have to expect that one more visitor will see the previous version. When testing it, reload twice before deciding it doesn't work.

  1. revalidatePath: by address

Sometimes you don't know which tags are involved in a page, or there aren't any. revalidatePath invalidates everything cached for a route:

revalidatePath('/venues') // A specific page
revalidatePath('/events/jazz-night') // A specific URL of a dynamic route
revalidatePath('/events/[slug]', 'page') // All event pages
revalidatePath('/events/[slug]', 'layout') // The event pages and everything below them
revalidatePath('/', 'layout') // Everything
  • The second argument is required if the route contains brackets, and omitted with literal addresses. The pattern can include the groups: '/(public)/events/[slug]' is also valid.
  • It works on the file structure. With rewrites, you have to give the destination, not the visible address.
  • It can be called in Server Actions and Route Handlers. In an action, if that route is being viewed, it's updated; in a Route Handler, it's marked for the next visit.
  • Under the hood it's the same system: Next.js gives each route implicit tags, and revalidatePath invalidates them.

Its limitation is the flip side of its convenience: it only reaches the routes you name. If you change an event and revalidate /events/jazz-night, the event page is updated, but the home page, the guide, the venue and the related events on other event pages stay the same. With tags you don't need to know which pages exist.

Keep revalidatePath for changes that affect a page rather than a piece of data, or for code without tags. The last line of the example clears everything: it's an emergency tool, not a habit.

  1. refresh: without touching the cache

Some screens read without a cache. After an action in the dashboard there's nothing to invalidate, but there is something to read again:

'use server'

import { refresh } from 'next/cache'

export async function archiveNotice(id: string) {
  await markAsArchived(id)
  refresh() // Repeats the current route's dynamic work; invalidates nothing on the server
}

It can only be called in Server Actions. Its browser equivalent is router.refresh() (02-03). It clears the pages stored for back and forward navigation, and keeps the prefetched routes. If a cached piece of data has changed, refresh will not show it: it'll serve the same entry again.

Without any of these calls, an action finishes and the screen stays as it was. It's a common oversight with uncached data: the write goes through fine and nobody sees it.

  1. What happens in the browser

The router keeps the RSC Payload of what was visited and prefetched in memory, for each item's stale time. That copy knows nothing about what happens on the server. This is what each call does with it:

Call Rerenders the current route Prefetched routes Stored for back and forward
updateTag Yes All cleared Cleared
revalidatePath in an action If it's showing the affected route Cleared Cleared
revalidateTag with { expire: 0 }, in an action Yes All cleared Cleared
revalidateTag with 'max' No Unchanged Unchanged
refresh Yes Kept Cleared
Any of them, from a Route Handler No Unchanged Unchanged

Three practical consequences follow:

  • The client-side effect is only for whoever runs the action. Another person with the home page open will keep seeing it as it was until they navigate and their stale has passed, or until they reload.
  • More is cleared than necessary. updateTag discards all prefetched routes, even if they don't carry the tag. It isn't wrong, just less efficient; visible links can be prefetched again.
  • Hidden pages keep their state. Remember from 02-01 that, with Cache Components, the last visited routes stay mounted. After an invalidation they keep their React state and refresh the server data when you go back to them.

If a piece of data has to be seen changing with the page open and without anyone doing anything, revalidation isn't the tool: polling is, as in LiveAvailability.

  1. Where they can be called from

Server Action Route Handler While rendering Inside 'use cache' Client Component proxy.ts
updateTag Yes No No No No No
revalidateTag Yes Yes No No No No
revalidatePath Yes Yes No No No No
refresh Yes No No No No No

You can't invalidate while rendering, and that makes sense: a Server Component can run at build time, during a prefetch or several times, and a read mustn't have side effects. If you find yourself wanting to ("refresh when the page is visited"), what you're after is a shorter cacheLife or no cache at all.

As for the moment within the function:

  • After the write is committed. With a transaction, outside it: if you notify before committing, another request can regenerate with the old data and leave it stored.
  • Before redirect, which works by throwing an exception: whatever comes after it doesn't run.
  • On the less traveled paths too: canceling, deleting, undoing, importing.

  1. Choosing

flowchart TD
    A["Something has changed"] --> B{"Is the data cached?"}
    B -- "No" --> C["refresh() if the current<br/>screen shows it"]
    B -- "Yes" --> D{"Must whoever changes it<br/>see it right away?"}
    D -- "Yes, in a Server Action" --> E["updateTag"]
    D -- "Yes, from a Route Handler" --> F["revalidateTag with expire: 0"]
    D -- "No" --> G{"Is the tag known?"}
    G -- "Yes" --> H["revalidateTag with 'max'"]
    G -- "No" --> I["revalidatePath"]
Situation Call Why
Your own form over cached data updateTag You see your own writes
Webhook from a content management system revalidateTag(…, 'max') Nobody waits; visits stay fast
Webhook that removes illegal or wrong content revalidateTag(…, { expire: 0 }) The old version mustn't be served even once more
Write over uncached data refresh There's nothing to invalidate
Presentation change on a page without tags revalidatePath It's the page that changes
Side effect for everyone else revalidateTag(…, 'max') The writer doesn't need to see it

They can be combined. A single action can hold two updateTag calls, a revalidateTag and a refresh.

  1. AgendaViva's notifications

Which tags each operation touches is domain knowledge, and it's best written down once. Create this module; the actions will use it from 06-01 on:

// lib/revalidation.ts
import 'server-only'
import { revalidateTag, updateTag } from 'next/cache'
import {
  EVENTS_TAG,
  VENUES_TAG,
  eventTag,
  venueTag,
} from '@/lib/tags'

// Server Actions only. With several slugs: the old one and the new one
export function invalidateEvent(...slugs: string[]): void {
  updateTag(EVENTS_TAG)
  for (const slug of slugs) updateTag(eventTag(slug))
}

// Server Actions only
export function invalidateVenue(...slugs: string[]): void {
  updateTag(VENUES_TAG)
  for (const slug of slugs) updateTag(venueTag(slug))
}

// After booking or canceling: the listings only show whether spots are left
export function notifyIfAvailabilityChanges(before: number, after: number): void {
  if ((before === 0) !== (after === 0)) revalidateTag(EVENTS_TAG, 'max')
}

And this is the table we'll stick to:

Operation Lesson Notification
Choosing the preferred district 06-01 None on data: the cookie isn't cached
Creating a draft 06-02 refresh if it stays on the dashboard; nothing public changes
Editing a published event 11-03 invalidateEvent(slug), or with both if the slug changes
Publishing 08-04 invalidateEvent(slug)
Canceling 11-03 invalidateEvent(slug)
Booking or canceling a booking 06-01 to 06-04 refresh and notifyIfAvailabilityChanges
Editing a venue No screen in the course invalidateVenue(slug)
Notification from an external system 07-03 revalidateTag with 'max', or with { expire: 0 }

Comments on the less obvious rows:

Creating a draft invalidates nothing public, because no public listing contains it. But publishing must expire event:slug, even though the event "wasn't" anywhere: someone may have visited its address earlier, and the absence was stored with that tag.

Booking doesn't use updateTag. Whoever books needs to see the spots, which are read without a cache, and refresh is enough for that. The listings show "Spots available" or "Fully booked", and that only changes when the last spot runs out or frees up. If every booking expired events, on a busy afternoon the home page would be regenerated nonstop: the cache would exist only on paper. It's the module's best example of how the precision of the interface determines the cost of the cache.

Editing a venue also changes its events' pages, which carry venue:slug thanks to the tag added after querying, and the listings, which carry venues.

9.1. Several instances

Everything above assumes one process. With several, invalidation is local: updateTag on instance A doesn't affect instance B, which will keep serving its own entries until they expire. Coordinating them needs a custom cache handler, with cacheHandlers, that shares the notifications through Redis or similar (11-05). Managed platforms usually take care of it. In the meantime, the cacheLife times set the maximum lag: another reason not to leave them unbounded.

  1. Trying it out today

With no actions yet, a temporary Route Handler lets you see the difference. Delete it when you're done:

// app/api/revalidate/route.ts — only for this exercise
import { revalidateTag } from 'next/cache'
import { EVENTS_TAG } from '@/lib/tags'

export async function POST(request: Request) {
  if (request.headers.get('x-key') !== process.env.REVALIDATION_KEY) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const immediate = new URL(request.url).searchParams.has('immediate')
  revalidateTag(EVENTS_TAG, immediate ? { expire: 0 } : 'max')
  return Response.json({ tag: EVENTS_TAG, immediate })
}
# .env.local: REVALIDATION_KEY=local-test
npm run build && npm run start

# In another terminal; first, change a title with npm run db:studio
curl -s localhost:3000/ | grep -c 'New title'                     # 0
curl -X POST -H 'x-key: local-test' localhost:3000/api/revalidate
curl -s localhost:3000/ | grep -c 'New title'                     # 0: the old version, and it's renewed
curl -s localhost:3000/ | grep -c 'New title'                     # 1

Leave a second between the last two, so the renewal finishes. Repeat with 'localhost:3000/api/revalidate?immediate', in quotes, and another title: the change shows up the first time. Then open the home page in the browser, change the title, send the notification with curl and navigate between pages: while the stale time lasts, the browser may keep showing what it had.

If the variable didn't exist, a missing x-key would be null, which isn't undefined, and the request would be rejected. For a real key, the comparison must be done in constant time; you'll see that in 07-03.

Common Mistakes and Tips

  • Invalidating before writing, or inside the transaction.
  • Putting the notification after redirect.
  • Using revalidateTag(…, 'max') after your own form and being surprised to see the previous version.
  • Believing the second argument sets the new lifetime.
  • Using refresh for cached data, or updateTag for uncached data.
  • Overusing revalidatePath('/', 'layout'). It works, and it clears everything on every change.
  • Expiring a collection tag with very frequent operations.
  • Forgetting the item tag when publishing: the stored null survives.
  • Expecting other browsers to update on their own.
  • A revalidation endpoint with GET or without protection.

Exercises

Exercise 1: choosing the call

Say what you'd call when: (a) an organizer corrects an event's time from the dashboard; (b) an external process imports 200 events every night; (c) someone marks a notice as read on a screen without a cache; (d) the city council asks for a poster to be taken down right now, through a system that calls an endpoint; (e) the legal text changes, read from the database on /legal with 'use cache' and no tags.

Solution

  • (a) invalidateEvent(slug), that is, updateTag on events and on event:slug. She must see her change.
  • (b) revalidateTag(EVENTS_TAG, 'max') once, at the end, plus the tag of each modified event. Notifying after each of the 200 would only trigger intermediate renewals.
  • (c) refresh().
  • (d) revalidateTag(eventTag(slug), { expire: 0 }) and the same with events: the old version mustn't be served again. updateTag isn't available in a Route Handler.
  • (e) revalidatePath('/legal') works. Better to give the function a tag and, from the action, call updateTag.

Exercise 2: reviewing an action

Find the four problems in this action and fix it. renameEvent writes to the database and returns the new slug.

'use server'

export async function rename(slug: string, title: string) {
  revalidateTag('event:' + slug, 'max')
  const newSlug = await renameEvent(slug, title)
  redirect(`/events/${newSlug}`)
  updateTag('Events')
}

Solution

  1. The first notification is sent before writing.
  2. It uses revalidateTag with 'max', and whoever renames would see the previous version.
  3. updateTag comes after redirect and doesn't run; what's more, the tag is events, lowercase.
  4. The new slug isn't invalidated, and its absence may be stored.
'use server'

import { redirect } from 'next/navigation'
import { invalidateEvent } from '@/lib/revalidation'

export async function rename(slug: string, title: string) {
  const newSlug = await renameEvent(slug, title)
  invalidateEvent(slug, newSlug)
  redirect(`/events/${newSlug}`)
}

What's missing is checking who calls it and what it receives, which comes first in a real action (06-03 and 08-06).

Exercise 3: predicting what's seen

Ana edits a title with updateTag on events and event:x. Before she saved, Bruno had the home page open, Carla had the page for x open and Diego has just arrived on the site. The event page was opened a minute ago. Say what each of them sees right after she saves, without reloading, and what would have to happen for them to see the new title.

Solution

  • Ana: the new title, in her action's response. Her router has cleared what was prefetched.
  • Bruno: the old one. His browser knows nothing. He'll see it when he reloads, or when he goes back to the home page once the stale time has passed.
  • Carla: the old one. Same as Bruno. LiveAvailability polls, but it only fetches spots.
  • Diego: on a full load, the new one. If he's the first to request the home page after the change, he waits while it's regenerated.

Conclusion

Reporting a change consists of marking tags or routes as stale or expired; the work is done when someone requests them. updateTag, in Server Actions, guarantees that the writer sees their change. revalidateTag with 'max' makes nobody wait, and with { expire: 0 } it prevents the old version from being served. revalidatePath works by address, and refresh repeats what isn't cached. The browser only finds out if the call comes from its own action. AgendaViva now has its notifications written in lib/revalidation.ts, waiting for someone to trigger them.

There's one area where the cache still doesn't shine: the first visit to an event page still shows a skeleton, because at build time it isn't known which slugs exist. In Static Route Generation with generateStaticParams we'll provide them.

© Copyright 2026. All rights reserved