cacheTag

cacheTag関数を使用すると、オンデマンドでキャッシュを無効化するためにデータにタグを付けることができます。キャッシュエントリにタグを関連付けることで、他のキャッシュデータに影響を与えずに特定のキャッシュエントリを選択的に削除または再検証できます。

使用方法

cacheTagを使用するには、next.config.jsファイルでdynamicIOフラグを有効にします:

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  experimental: {
    dynamicIO: true,
  },
}

export default nextConfig

cacheTag関数は単一の文字列値、または文字列配列を受け取ります。

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を使用してオンデマンドでキャッシュを無効化できます:

'use server'

import { revalidateTag } from 'next/cache'

export default async function submit() {
  await addPost()
  revalidateTag('my-data')
}

知っておくと良いこと

  • べき等性タグ: 同じタグを複数回適用しても追加効果はありません。
  • 複数タグ: cacheTagに配列を渡すことで、単一のキャッシュエントリに複数のタグを割り当てられます。
cacheTag('tag-one', 'tag-two')

コンポーネントや関数へのタグ付け

キャッシュされた関数やコンポーネント内でcacheTagを呼び出してデータにタグを付けます:

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 //...
}

外部データからのタグ作成

非同期関数から返されたデータを使用してキャッシュエントリにタグを付けることができます。

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を使用して、必要な時に特定のタグのキャッシュを無効化できます:

'use server'

import { revalidateTag } from 'next/cache'

export async function updateBookings() {
  await updateBookingData()
  revalidateTag('bookings-data')
}

On this page