Capítulo 182 de 456

updateTag

Core Idea

Invalidate a cache tag on-demand from inside a Server Action, forcing the next request to wait for fresh data instead of serving stale content. Purpose-built for read-your-own-writes UX (e.g. immediately showing a newly created post).

Key Concepts

  • updateTag(tag: string): Expires cached data for tag immediately; can only be called from a Server Action.
  • Read-your-own-writes: The pattern where a user's own mutation is guaranteed to reflect in the very next read, not a stale cached copy.
  • Tag assignment: Data must be tagged first via fetch(url, { next: { tags: ['posts'] } }) or cacheTag('posts') inside a 'use cache' function.

Code Examples

'use server'

import { updateTag } from 'next/cache'
import { redirect } from 'next/navigation'

export async function createPost(formData: FormData) {
  const post = await db.post.create({ data: { /* ... */ } })

  updateTag('posts')
  updateTag(`post-${post.id}`)

  redirect(`/posts/${post.id}`)
}
  • O que demonstra: Após criar um registro, invalida as tags que afetam a listagem e o detalhe antes do redirect, garantindo que a próxima renderização já veja o dado novo.

Anti-patterns

  • Chamar updateTag fora de Server Action: lança erro em tempo de execução ("updateTag can only be called from within a Server Action"); use revalidateTag em Route Handlers.

Key Takeaways

  1. updateTag é exclusivo de Server Actions; para Route Handlers/webhooks use revalidateTag.
  2. Ao contrário de revalidateTag com profile="max" (stale-while-revalidate), updateTag nunca serve conteúdo obsoleto: a próxima requisição espera o dado fresco.
  3. Tags de até 256 caracteres, case-sensitive.
  4. Combine com redirect() para o padrão clássico "criar → invalidar → redirecionar já com dado atualizado".

Connects To

  • revalidateTag: alternativa para Route Handlers e cenários stale-while-revalidate.
  • revalidatePath: invalidação por caminho em vez de tag.