cacheTag
cacheTag
関数を使用すると、オンデマンド無効化のためにキャッシュされたデータにタグを付けることができます。タグをキャッシュエントリと関連付けることで、他のキャッシュデータに影響を与えずに特定のキャッシュエントリを選択的に削除または再検証することができます。
使い方
cacheTag
を使用するには、next.config.js
ファイルでdynamicIO
フラグを有効にしてください:
next.config.ts
TypeScript
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
dynamicIO: true,
},
}
export default nextConfig
cacheTag
関数は単一の文字列値または文字列配列を受け取ります。
app/data.ts
TypeScript
import { unstable_cacheTag as cacheTag } from 'next/cache'
export async function getData() {
'use cache'
cacheTag('my-data')
const data = await fetch('/api/data')
return data
}
その後、別の関数でrevalidateTag
APIを使用してオンデマンドでキャッシュを削除することができます。例えば、ルートハンドラーやサーバーアクションなどで使用できます:
app/action.ts
TypeScript
'use server'
import { revalidateTag } from 'next/cache'
export default async function submit() {
await addPost()
revalidateTag('my-data')
}
補足
- べき等なタグ:同じタグを複数回適用しても追加の効果はありません。
- 複数のタグ:
cacheTag
に配列を渡すことで、単一のキャッシュエントリに複数のタグを割り当てることができます。
cacheTag('tag-one', 'tag-two')
例
コンポーネントまたは関数にタグを付ける
キャッシュされた関数またはコンポーネント内でcacheTag
を呼び出して、キャッシュデータにタグを付けます:
app/components/bookings.tsx
TypeScript
import { unstable_cacheTag as cacheTag } from 'next/cache'
interface BookingsProps {
type: string
}
export async function Bookings({ type = 'haircut' }: BookingsProps) {
'use cache'
cacheTag('bookings-data')
async function getBookingsData() {
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
return data
}
return //...
}
外部データからタグを作成する
非同期関数から返されたデータを使用して、キャッシュエントリにタグを付けることができます。
app/components/bookings.tsx
TypeScript
import { unstable_cacheTag as cacheTag } from 'next/cache'
interface BookingsProps {
type: string
}
export async function Bookings({ type = 'haircut' }: BookingsProps) {
async function getBookingsData() {
'use cache'
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
cacheTag('bookings-data', data.id)
return data
}
return //...
}
タグ付きキャッシュの無効化
revalidateTag
を使用して、必要なときに特定のタグのキャッシュを無効化できます:
app/actions.ts
TypeScript
'use server'
import { revalidateTag } from 'next/cache'
export async function updateBookings() {
await updateBookingData()
revalidateTag('bookings-data')
}