コンテンツにスキップ

updateTag

updateTagを使用すると、キャッシュされたデータを、Server Actions内から特定のキャッシュタグでオンデマンドで更新できます。

この関数は、ユーザーが変更(投稿の作成など)を行い、UIがすぐにその変更を表示し、古いデータを表示しないようなRead-Your-Own-Writesシナリオのために設計されています。

使用方法

updateTagは、Server Actions内から**のみ**呼び出すことができます。Route Handlers、Client Components、またはその他のコンテキストでは使用できません。

Route Handlersやその他のコンテキストでキャッシュタグを無効化する必要がある場合は、代わりにrevalidateTagを使用してください。

知っておくと便利: updateTagは、指定されたタグのキャッシュデータを直ちに期限切れにします。次のリクエストでは、古いコンテンツをキャッシュから提供するのではなく、新しいデータを取得するために待機するため、ユーザーは変更をすぐに確認できます。

Parameters

updateTag(tag: string): void;
  • tag: 更新したいデータに関連付けられたキャッシュタグを表す文字列。256文字を超えることはできません。この値は大文字と小文字を区別します。

タグは、まずキャッシュされたデータに割り当てる必要があります。これは次の2つの方法で行えます。

  • 外部APIリクエストのキャッシュにfetchとともにnext.tagsオプションを使用する
fetch(url, { next: { tags: ['posts'] } })
  • 'use cache'ディレクティブとともに、キャッシュされた関数またはコンポーネント内でcacheTagを使用する
import { cacheTag } from 'next/cache'
 
async function getData() {
  'use cache'
  cacheTag('posts')
  // ...
}

戻り値

updateTagは値を返しません。

revalidateTagとの違い

updateTagrevalidateTagはどちらもキャッシュデータを無効化しますが、目的が異なります。

  • updateTag:

    • Server Actionでのみ使用可能
    • 次回のリクエストでは新しいデータの取得を待機(古いコンテンツは提供されない)
    • Read-Your-Own-Writesシナリオ向け
  • revalidateTag:

    • Server ActionおよびRoute Handlerで使用可能
    • profile="max"(推奨)の場合:バックグラウンドで新しいデータを取得しながら、キャッシュされたデータを提供する(stale-while-revalidate)
    • カスタムプロファイルの場合:高度な使用のために、任意のキャッシュライフプロファイルに構成可能
    • プロファイルなしの場合:updateTagと同等のレガシー動作

読み取り後すぐに書き込み(Read-Your-Own-Writes)とServer Action

app/actions.ts
'use server'
 
import { updateTag } from 'next/cache'
import { redirect } from 'next/navigation'
 
export async function createPost(formData: FormData) {
  const title = formData.get('title')
  const content = formData.get('content')
 
  // Create the post in your database
  const post = await db.post.create({
    data: { title, content },
  })
 
  // Invalidate cache tags so the new post is immediately visible
  // 'posts' tag: affects any page that displays a list of posts
  updateTag('posts')
  // 'post-{id}' tag: affects the individual post detail page
  updateTag(`post-${post.id}`)
 
  // Redirect to the new post - user will see fresh data, not cached
  redirect(`/posts/${post.id}`)
}

Server Action外での使用時のエラー

app/api/posts/route.ts
import { updateTag } from 'next/cache'
 
export async function POST() {
  // This will throw an error
  updateTag('posts')
  // Error: updateTag can only be called from within a Server Action
 
  // Use revalidateTag instead in Route Handlers
  revalidateTag('posts', 'max')
}

updateTagの使用場面

updateTagを使用する状況:

  • Server Action内である
  • Read-Your-Own-Writesのための即時キャッシュ無効化が必要
  • 次回のリクエストで更新されたデータが表示されることを保証したい

revalidateTagを使用する状況:

  • Route Handlerまたはその他のアクション以外のコンテキストである
  • stale-while-revalidateセマンティクスが必要
  • キャッシュ無効化のためのWebhookまたはAPIエンドポイントを構築している