紀錄工作經驗、相關知識,解決技術相關問題。

Next

Next.js cacheTag 用法:多標籤寫法、長度與數量上限、搭配 updateTag 與 revalidateTag 清除快取

Next.js cacheTag 用法:多標籤寫法、長度與數量上限、搭配 updateTag 與 revalidateTag 清除快取 特色圖片

Next.js cacheTag 是 next/cache 提供的函式,用來幫 use cache 的快取資料加上標籤,之後資料異動時只要指定標籤,就能清掉相關的快取,不影響其他快取資料。本文以 Next.js 16(範例在 16.4.3 執行)說明 cacheTag 的基本寫法、一次掛多個標籤、依資料內容產生標籤、標籤長度與數量上限、只能在快取範圍內呼叫的限制,以及搭配 updateTag、revalidateTag 清除快取的方式。use cache 的啟用與快取鍵可以先看〈Next.js use cache 指令用法〉,快取壽命的設定請看〈Next.js cacheLife 用法〉,本文不再重複。

cacheTag 基本寫法

cacheTag 要搭配 use cache,因此先在 next.config.ts 開啟 cacheComponents:

// next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  cacheComponents: true,
}

export default nextConfig

接著在快取函式裡呼叫 cacheTag,傳入一個或多個字串:

// app/data.ts
import { cacheLife, cacheTag } from 'next/cache'

export async function getPosts() {
  'use cache'
  cacheLife('hours')
  cacheTag('posts')
  return { at: new Date().toISOString() }
}

cacheTag 只是幫快取資料貼上標籤,本身不會讓快取過期。要清除快取,得在 Server Action 呼叫 updateTag('posts'),或在 Server Action、Route Handler 呼叫 revalidateTag('posts', 'max'),後面「搭配 updateTag 與 revalidateTag」一節會說明兩者的差別。

除了 cacheTag,用 fetch 抓外部 API 時也可以用 next.tags 選項貼標籤,清除方式相同:

fetch(url, { next: { tags: ['posts'] } })

一次掛多個標籤

同一筆快取可以同時掛多個標籤,把字串依序傳進去即可:

export async function getPosts() {
  'use cache'
  cacheLife('hours')
  cacheTag('posts', 'home')
  return { at: new Date().toISOString() }
}

這筆快取不論是 posts 還是 home 被清除,都會重新產生。在頁面上依序送出三個 Server Action(updateTag('POSTS')、updateTag('home')、updateTag('posts')),頁面顯示的產生時間如下:

posts at: 2026-11-03T06:26:13.306Z
updateTag('POSTS') -> posts at: 2026-11-03T06:26:13.306Z
updateTag('home')  -> posts at: 2026-11-03T06:26:24.951Z
updateTag('posts') -> posts at: 2026-11-03T06:26:27.962Z
測試頁依序按下 updateTag('POSTS')、updateTag('home')、updateTag('posts') 三個按鈕,POSTS 後時間不變,home 與 posts 後時間都更新

Next.js 16.4.3 next dev、無頭 Chrome 156 用滑鼠依序點擊三個 Server Action 按鈕,右側為每次點擊後讀到的頁面文字。

home 和 posts 都會讓時間更新;POSTS 沒有作用,因為標籤區分大小寫,POSTS 和 posts 是不同的標籤。

同一個標籤重複套用沒有額外效果,例如 cacheTag('posts', 'posts') 和 cacheTag('posts') 結果相同,不需要特別去除重複。

依資料內容產生標籤

標籤不一定要寫死,可以用快取函式取得的資料組出來。常見做法是一個共用標籤加上一個以 ID 區分的標籤:

export async function getProduct(id: string) {
  'use cache'
  cacheLife('hours')
  const product = await db.product.findUnique({ where: { id } })
  cacheTag('products', `product-${product.id}`)
  return product
}

/product/1 與 /product/2 兩頁各自是一筆快取,標籤分別是 products+product-1、products+product-2。清除 product-1 只會讓商品 1 重新產生,清除 products 則兩頁都會更新:

初始               p1 06:26:05.057Z  p2 06:26:05.621Z
清除 product-1 後  p1 06:26:16.041Z  p2 06:26:05.621Z
清除 products 後   p1 06:26:16.459Z  p2 06:26:16.631Z

這樣在後台修改單一商品時只清 product-<id>,批次匯入商品時再清 products,不必每次都讓所有商品頁重新產生。

標籤長度與數量上限

單次 cacheTag() 呼叫最多接受 128 個標籤,每個標籤最長 256 個字元。超過 256 字元的標籤會被略過,同一次呼叫中第 128 個之後的標籤會被丟棄,兩種情況都會在終端機印出警告。下面故意傳入一個 257 字元的標籤,以及一次 130 個標籤(t0~t129):

async function getData() {
  'use cache'
  cacheLife('hours')
  cacheTag('x'.repeat(257))
  cacheTag(...Array.from({ length: 130 }, (_, i) => `t${i}`))
  return { at: new Date().toISOString() }
}

頁面照常回應 200,next dev 終端機輸出(257 個 x 以省略號表示):

Warning: invalid tags passed to `cacheTag()`:
tag: "xxxx…xxxx" exceeded max length of 256
Warning: exceeded max tag count for `cacheTag()`, dropped tags: t128, t129

因為只是警告不會報錯,標籤用文章標題、網址這類長度不固定的字串組成時,超過上限的標籤會在沒有錯誤的情況下失效:之後呼叫 revalidateTag 或 updateTag 清除這個標籤,不會有任何作用。標籤建議用固定前綴加上 ID,例如 product-123。

只能在 use cache 範圍內呼叫

cacheTag 必須在使用 use cache 或 use cache: private 的函式或元件裡呼叫。在沒有快取的元件裡呼叫,沒有快取資料可以貼標籤,會直接丟錯:

import { cacheTag } from 'next/cache'

export default async function Page() {
  cacheTag('outside')
  return <p>outside</p>
}

next dev 開啟這頁回應 500,終端機錯誤訊息:

Error: Route "/tests/nextjs-cachetag/outside": `cacheTag()` can only be called inside a `"use cache"` or `"use cache: private"` function.
Learn more: https://nextjs.org/docs/messages/cache-tag-outside-use-cache

修正方式是把 cacheTag 移進要貼標籤的那個快取函式:

import { cacheTag } from 'next/cache'

async function getProducts() {
  'use cache'
  cacheTag('products')
  return db.product.findMany()
}

export default async function Page() {
  const products = await getProducts()
  return <p>{products.length}</p>
}

如果這個函式本來就不打算快取,直接刪掉 cacheTag 即可。

搭配 updateTag 與 revalidateTag 清除快取

兩個函式都用標籤清除快取,差別在下一個請求會不會先拿到舊資料,以及可以在哪裡呼叫:

函式可呼叫的位置下一個請求適用情境
updateTag(tag)只能在 Server Actions等待新資料,不給舊內容表單送出後要立刻看到自己的修改
revalidateTag(tag, 'max')Server Actions、Route Handlers先拿舊內容,背景重新產生部落格、商品目錄這類稍有延遲可接受的內容
revalidateTag(tag, { expire: 0 })Server Actions、Route Handlers不給舊內容,等待重新產生Route Handler、webhook 這類不能用 updateTag 的地方

表單送出後清除快取,用 updateTag:

// app/actions.ts
'use server'

import { updateTag } from 'next/cache'

export async function createPost(formData: FormData) {
  const post = await db.post.create({ data: { title: String(formData.get('title')) } })
  updateTag('posts')
  updateTag(`post-${post.id}`)
}

Route Handler 不能呼叫 updateTag,在 Route Handler 裡呼叫會回應 500,終端機錯誤訊息:

Error: updateTag can only be called from within a Server Action. To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag

給 webhook 或外部服務呼叫的清除端點改用 revalidateTag:

// app/api/revalidate/route.ts
import type { NextRequest } from 'next/server'
import { revalidateTag } from 'next/cache'

export async function GET(request: NextRequest) {
  const tag = request.nextUrl.searchParams.get('tag')
  if (!tag) return Response.json({ revalidated: false })
  revalidateTag(tag, 'max')
  return Response.json({ revalidated: true, tag })
}

用 'max' 清除 posts 後連續請求兩次頁面,第一次仍拿到舊的產生時間,第二次才是新的:

清除前           posts at: 2026-11-03T06:26:12.671Z
清除後第 1 次    posts at: 2026-11-03T06:26:12.671Z
清除後第 2 次    posts at: 2026-11-03T06:26:13.306Z

這就是先給舊內容、背景重新產生的行為。重新驗證是由請求觸發,不是在呼叫 revalidateTag 當下執行,所以掛同一個標籤的多個頁面,會在各自被造訪時才重新產生。要讓下一個請求直接拿新資料,把第二個參數換成 { expire: 0 }。

revalidateTag 只傳一個參數的寫法已經棄用,要加上第二個參數(官方建議 'max')。兩個函式各自的參數與更多情境,之後會在 updateTag 與 revalidateTag 的文章分別說明。

從 unstable_cacheTag 升級

cacheTag 在 Next.js v16.0.0 成為穩定 API,unstable_cacheTag 同時棄用。舊專案只要把匯入改成:

import { cacheTag } from 'next/cache'

如果專案用的是 fetch 的 next.tags,而不是 cacheTag,標籤清除不生效時可以參考〈Next.js fetch next.tags:revalidateTag 沒清除快取的原因〉。

參考資料與延伸閱讀

發佈留言