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

Next

Next.js use cache 指令用法:函式、元件與檔案層級快取、cacheLife 與 cacheTag

Next.js use cache 指令用法:函式、元件與檔案層級快取、cacheLife 與 cacheTag 特色圖片

Next.js 的 use cache 指令把一個 async 函式、元件或整個檔案標記為可快取:同樣的參數第二次呼叫時,直接拿上次的回傳值,不再重新執行函式內容。本文以 Next.js 16(範例在 16.4.3 執行)說明啟用方式、三種放置位置、快取鍵怎麼組成、cacheLife 與 cacheTag 的搭配,以及 cookies() 放錯位置的錯誤訊息。

use cache 基本寫法

use cache 是 Cache Components 的功能,要先在 next.config.ts 開啟 cacheComponents。官方建議同時明確設定 partialPrefetching,沒設定時會輸出警告:

import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  cacheComponents: true,
  partialPrefetching: true,
}

export default nextConfig

接著在函式或元件的第一行寫 'use cache'。被快取的函式與元件都必須是 async:

import { cacheLife } from 'next/cache'

// 函式層級:快取回傳值,參數會成為快取鍵的一部分
async function getCachedTime(label: string) {
  'use cache'
  cacheLife('minutes')
  return { label, at: new Date().toISOString() }
}

// 元件層級:快取整個元件的輸出
async function CachedCard() {
  'use cache'
  cacheLife('hours')
  const a = await getCachedTime('A')
  const a2 = await getCachedTime('A')
  const b = await getCachedTime('B')
  return (
    <ul>
      <li>A 第一次:{a.at}</li>
      <li>A 第二次:{a2.at}</li>
      <li>B:{b.at}</li>
    </ul>
  )
}

use cache 從 Next.js 15.0.0 以實驗功能推出,16.0.0 起穩定並改由 cacheComponents 啟用。16.0.0 之前的 experimental.useCache、experimental.dynamicIO 寫法要照官方 Version 16 升級說明改掉。

三種放置位置

位置寫法快取範圍
函式層級async 函式第一行寫 'use cache'這個函式的回傳值
元件層級async 元件第一行寫 'use cache'這個元件渲染出來的結果
檔案層級檔案最上方寫 'use cache'檔案內每一個 export 的函式,每個都必須是 async

檔案層級放在 page、layout 時,每個路由區段是各自獨立的快取。想讓整條路由都預先渲染,page、layout 與平行路由的插槽檔案都要各自加上 'use cache':

'use cache'

export default async function Page() {
  return <main>{/* ... */}</main>
}

快取鍵:哪些東西不同就會分開快取

use cache 的快取鍵由以下幾項組成:

  1. Build ID:每次建置都不同,換版部署後舊快取全部失效(有設定 deploymentId 時改用它)
  2. Function ID:函式在程式碼中的位置與簽章產生的雜湊
  3. 可序列化的參數:元件的 Props 或函式的參數
  4. HMR refresh hash:只在開發模式,熱更新後快取失效

函式引用外層作用域的變數時,這些變數也會自動算進快取鍵。上面的範例中,getCachedTime('A') 呼叫兩次拿到同一筆快取,getCachedTime('B') 參數不同,是另一筆快取。

下圖是把上面兩段程式碼放進頁面、next build 後用 next start 開啟的結果。A 的兩次呼叫時間完全相同;最下面一行是放在 <Suspense> 內、先呼叫 await connection() 的未快取元件,每次重新整理都會變:

use cache 範例頁面:A 兩次呼叫時間相同,B 為另一筆快取,最下方未快取的時間每次請求都不同

Next.js 16.4.3 next start、Chrome 執行結果

同一次建置的輸出中,這個路由標示為 ◐(Partial Prerender),Revalidate 欄是 1h、Expire 欄是 1d,也就是外層 CachedCard 的 cacheLife('hours'):

├ ◐ /tests/nextjs-use-cache-directive                                     1h      1d

參數與回傳值必須可序列化

快取函式的參數與回傳值都必須可序列化。

  • 可以當參數:string、number、boolean、null、undefined、一般物件、陣列、Date、Map、Set、TypedArray、ArrayBuffer,以及只做穿透(pass-through)的 React 元素
  • 回傳值:上面全部,再加上 JSX
  • 不支援:class 實例、函式(穿透除外)、Symbol、WeakMap、WeakSet、URL 實例

「穿透」是指快取元件收到 children 或 Server Action,只把它原封不動放進回傳的 JSX,不讀取、不呼叫。這樣 children 不影響快取項目,裡面可以放沒有快取的動態元件:

import type { ReactNode } from 'react'

async function CachedWrapper({ children }: { children: ReactNode }) {
  'use cache'
  return (
    <div className="wrapper">
      <header>Cached Header</header>
      {children}
    </div>
  )
}

cacheLife:設定快取多久

沒有呼叫 cacheLife 時套用 default profile:用戶端 stale 5 分鐘、伺服器 revalidate 15 分鐘、expire 不依時間過期。官方建議每個 use cache 範圍都明確寫 cacheLife,在呼叫處就看得出快取多久。cacheLife 從 next/cache 匯入,只能在快取指令範圍內呼叫,寫在檔案頂層會丟出錯誤。

Profilestalerevalidateexpire
seconds30 秒1 秒1 分鐘
minutes5 分鐘1 分鐘1 小時
hours5 分鐘1 小時1 天
days5 分鐘1 天1 週
weeks5 分鐘1 週30 天
max5 分鐘30 天1 年
  • stale:用戶端不問伺服器、直接用快取的時間。用戶端路由至少會用 30 秒,不論設定多短。
  • revalidate:超過這段時間後的下一個請求,先回舊內容,再在背景重新產生。
  • expire:超過這段時間都沒有請求,下一個請求要等新內容產生完。

use cache 互相巢狀時,外層有明確寫 cacheLife 就以外層為準,不論內層比較長或比較短;外層沒寫時套用 default,內層較短的壽命會把外層縮短。上面範例的路由顯示 1h/1d,就是外層 hours 生效的結果。

cacheTag 與 updateTag:資料更新後清除快取

用 cacheTag 幫快取資料加上標籤,資料異動後在 Server Action 呼叫 updateTag 讓這個標籤的快取立即過期,下一個請求會等待新資料:

// page.tsx
import { cacheLife, cacheTag } from 'next/cache'

async function getCachedTime(label: string) {
  'use cache'
  cacheLife('minutes')
  cacheTag('demo-time')
  return { label, at: new Date().toISOString() }
}
// actions.ts
'use server'

import { updateTag } from 'next/cache'

export async function refreshDemoTime() {
  updateTag('demo-time')
}

把 refreshDemoTime 接到頁面上的 <form action={refreshDemoTime}> 送出後,前面截圖中的 A、B 時間都換成送出當下的時間,連外層用 cacheLife('hours') 快取的 CachedCard 也一起更新。

函式可呼叫的位置行為
updateTag(tag)只能在 Server Actions立即過期,下一個請求等待新資料
revalidateTag(tag, 'max')Server Functions、Route Handlers標記為過期,下一個請求先拿舊內容、背景重新產生

revalidateTag 只傳一個參數的寫法已經棄用,要加上第二個參數(官方建議 'max')。

常見錯誤:在 use cache 裡呼叫 cookies()

快取函式與元件不能使用 cookies()、headers()、searchParams 這類請求期間才有的 API,被快取函式呼叫到的輔助函式也一樣。下面的寫法在 next build 時會失敗:

import { cookies } from 'next/headers'

async function getTheme() {
  'use cache'
  const store = await cookies()
  return store.get('theme')?.value ?? 'light'
}
Error: Route "/tests/nextjs-use-cache-directive/cookies-error": `cookies()` can't be read inside `"use cache"`. Read it outside the cached function and pass what you need as an argument.
Learn more: https://nextjs.org/docs/messages/next-request-in-use-cache

動態渲染的路由不一定在建置時就出錯,官方提醒可能 next build 通過、到 next start 執行時才出現同一個錯誤。修正方式是在快取範圍外讀取 cookie,把值當參數傳進去,cookie 的值也就成為快取鍵的一部分:

import { Suspense } from 'react'
import { cookies } from 'next/headers'
import { cacheLife } from 'next/cache'

async function getThemeLabel(theme: string) {
  'use cache'
  cacheLife('hours')
  return `目前主題:${theme}`
}

async function Theme() {
  const theme = (await cookies()).get('theme')?.value ?? 'light'
  const label = await getThemeLabel(theme)
  return <p>{label}</p>
}

export default function Page() {
  return (
    <Suspense fallback={<p>載入中…</p>}>
      <Theme />
    </Suspense>
  )
}

沒有帶 cookie 時輸出「目前主題:light」,帶 Cookie: theme=dark 時輸出「目前主題:dark」。

draftMode() 是例外:可以在 use cache 內讀 isEnabled,但不能呼叫 enable()、disable()。Draft Mode 開啟時,所有快取函式與元件每次請求都會重新執行,結果不寫入快取。

使用前要知道的限制

  • 預設存在記憶體:預設以記憶體 LRU 儲存。自架 Node.js 伺服器會跨請求保留,可用 cacheMaxMemorySize 控制大小;Serverless 環境每個請求可能是不同的執行個體,快取通常不會保留。需要共用的快取可以改用 'use cache: remote' 搭配平台提供的快取處理器。
  • 換版就失效:快取鍵包含 Build ID(或 deploymentId),新部署不會沿用舊快取。
  • 不支援靜態匯出:Node.js 伺服器與 Docker 容器支援,靜態匯出(Static export)不支援。
  • 需要 Node.js runtime:Cache Components 不支援 runtime 路由區段設定,runtime = 'edge' 與 runtime = 'nodejs' 的 export 都要移除。
  • React.cache 是隔離的:在 use cache 外面用 React.cache 存的值,進到 use cache 裡讀不到,要傳資料進去請用參數。
  • 建置卡住 50 秒:把 cookies() 回傳的 Promise 這類執行期資料當 Props 傳進快取元件,建置時快取函式會一直等它,50 秒後出現 Filling a cache during prerender timed out 錯誤。先在外面 await 取得值,再把值傳進去。
  • 除錯:設定環境變數 NEXT_PRIVATE_DEBUG_CACHE=1 會輸出詳細快取記錄;開發模式中快取函式的 console.log 會加上 Cache 前綴。

cacheComponents 開啟後,App Router 預設就採用 Partial Prerendering,舊的 experimental.ppr 設定已移除。PPR 的靜態外殼與串流概念可以參考 Next.js PPR 教學:結合 SSG 快取速度與 SSR 即時資料的混合渲染解析,設定方式以本文與官方文件的 cacheComponents 為準。

參考資料與延伸閱讀

發佈留言