Next.js cacheLife 是 next/cache 提供的函式,用來設定 use cache 快取的壽命:用戶端可以直接用多久、伺服器多久在背景重新產生、多久沒人請求就整個過期。本文以 Next.js 16(範例在 16.4.3 執行)說明內建 profile 的數值、stale/revalidate/expire 三個屬性的意義、在 next.config.ts 自訂與覆寫 profile、行內物件寫法,以及巢狀快取時以哪一層為準。use cache 本身的啟用方式、快取鍵與序列化限制,可以先看〈Next.js use cache 指令用法〉,本文不再重複。
cacheLife 基本寫法
cacheLife 要搭配 use cache,而 use cache 需要在 next.config.ts 開啟 cacheComponents。從 next/cache 匯入後,在快取函式或元件裡傳入 profile 名稱:
// app/blog/page.tsx
import { cacheLife } from 'next/cache'
export default async function Page() {
'use cache'
cacheLife('days')
return <p>preset days: {new Date().toISOString()}</p>
}
next build 輸出的路由表會列出這個頁面的 Revalidate 與 Expire,也就是 days 的 1 天與 1 週:
Route (app) Revalidate Expire
├ ○ /tests/nextjs-cachelife/preset 1d 1w

Next.js 16.4.3 next build 的路由表節錄與 next start 的回應標頭(Windows 11、Node.js v22.20.0);這次建置的 next.config.ts 沒有自訂或覆寫 profile,所以 override-default 顯示的是內建 default 的 15m 與 1y。
使用時有三條規則:
- 只能在快取指令範圍內呼叫:寫在
'use cache'的檔案、函式或元件裡。寫在檔案頂層會丟錯。 - 在定義快取的地方直接呼叫:官方建議不要把
cacheLife包進共用工具函式,讓人一看呼叫處就知道快取多久。 - 每次執行只跑一次:可以寫在不同的條件分支,但同一次函式呼叫只能有一個
cacheLife被執行。
把 cacheLife 寫在檔案頂層,開啟頁面時會出現這個錯誤:
Error: Route "/tests/nextjs-cachelife/err-module": `cacheLife()` can only be called inside a `"use cache"` or `"use cache: private"` function.
Learn more: https://nextjs.org/docs/messages/cache-life-outside-use-cache
cacheLife 在 Next.js 16.0.0 穩定,舊的 unstable_cacheLife 已棄用,從 next/cache 改成匯入 cacheLife 即可。
內建 profile 的數值
Next.js 內建 7 個 profile。沒有呼叫 cacheLife 時套用 default,官方建議每個 use cache 範圍都明確寫上 profile:
| Profile | stale | revalidate | expire |
|---|---|---|---|
default | 5 分鐘 | 15 分鐘 | 不過期(never) |
seconds | 30 秒 | 1 秒 | 1 分鐘 |
minutes | 5 分鐘 | 1 分鐘 | 1 小時 |
hours | 5 分鐘 | 1 小時 | 1 天 |
days | 5 分鐘 | 1 天 | 1 週 |
weeks | 5 分鐘 | 1 週 | 30 天 |
max | 5 分鐘 | 30 天 | 1 年 |
依內容更新頻率挑選。官方對各 profile 的適用情境:default 是一般內容;seconds 適合股價、比分,minutes 適合動態牆、新聞,hours 適合商品庫存、天氣,days 適合部落格文章,weeks 適合 Podcast、電子報,max 適合法律條款、封存內容。
stale、revalidate、expire 的意義
| 屬性 | 作用在 | 意義 |
|---|---|---|
stale | 用戶端 | 用戶端路由器不問伺服器、直接用快取內容的時間 |
revalidate | 伺服器 | 超過這段時間後的請求,先回快取版本,再在背景重新產生並更新快取 |
expire | 伺服器 | 超過這段時間都沒有請求,下一個請求由伺服器同步重新產生,要等新內容 |
三個屬性的單位都是秒。revalidate 的行為類似 ISR(Incremental Static Regeneration):讀者先拿到舊內容,新內容在背景產生。expire 則是上限,太久沒人看的快取,下一個請求就不再回舊內容。
同時設定 revalidate 與 expire 時,expire 必須大於 revalidate。寫成 cacheLife({ revalidate: 3600, expire: 600 }),開啟頁面時會丟出:
Error: If providing both the revalidate and expire options, the expire option must be greater than the revalidate option. The expire option indicates how many seconds from the start until it can no longer be used.
stale 控制的是用戶端快取
stale 管的是用戶端的 Client Cache,不是 Cache-Control 標頭。伺服器把這個值放在 x-nextjs-stale-time 回應標頭,用戶端路由器依此決定何時重新驗證。幾個要注意的地方:
- 最少 30 秒:不論設定多短,用戶端至少保留 30 秒,避免預先載入(prefetch)的連結在使用者點下去前就過期。這個下限只套用在依時間過期的情況。
- Server Action 會清空用戶端快取:在 Server Action 呼叫
revalidateTag、revalidatePath、updateTag或refresh時,整個用戶端快取立即清除,不受stale限制。 - 和
staleTimes的關係:staleTimes是影響所有路由的全域設定,cacheLife可以針對單一函式或路由設定。修改staleTimes.static也會一併改掉defaultprofile 的stale。
在 next.config 自訂 cacheLife profile
內建 profile 不合用時,在 next.config.ts 的 cacheLife 選項定義自己的 profile,例如 stale 10 分鐘、revalidate 1 小時、expire 1 天的 editorial:
// next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
cacheLife: {
editorial: {
stale: 600, // 10 分鐘
revalidate: 3600, // 1 小時
expire: 86400, // 1 天
},
},
}
export default nextConfig
之後在任何快取範圍用名稱呼叫:
// app/editorial/page.tsx
import { cacheLife } from 'next/cache'
export default async function Page() {
'use cache'
cacheLife('editorial')
return <p>custom editorial: {new Date().toISOString()}</p>
}
建置後路由表顯示 1h/1d;用 next start 開啟頁面,回應標頭的 x-nextjs-stale-time 是 600:
├ ○ /tests/nextjs-cachelife/custom 1h 1d
x-nextjs-stale-time: 600
Cache-Control: s-maxage=3600, stale-while-revalidate=82800
自訂 profile 的規則:
stale、revalidate、expire都是選填的number,沒寫的屬性沿用defaultprofile 的值。expire必須比revalidate長。- Next.js 16.0.0 起是頂層的
cacheLife選項;16.0.0 之前寫在experimental.cacheLife,升級時要搬出來。 cacheLife函式的型別簽章會在next dev、next build或next typegen時依next.config.ts產生,覆寫過的 profile 在編輯器的自動完成與 JSDoc 提示會顯示你設定的數值。
覆寫內建 profile
在 cacheLife 選項裡用內建的名稱(default、seconds、minutes、hours、days、weeks、max)定義,就會覆寫那個 profile。覆寫 default 的影響最大:所有沒呼叫 cacheLife 的 use cache 範圍都會跟著改。下面把 default 的 revalidate 改成 1 小時:
// next.config.ts
const nextConfig = {
cacheComponents: true,
cacheLife: {
default: {
stale: 300, // 5 分鐘
revalidate: 3600, // 1 小時
expire: 86400, // 1 天
},
},
}
export default nextConfig
一個只寫 'use cache'、沒呼叫 cacheLife 的頁面,原本建置輸出是 15m/1y,加上這段設定後變成 1h/1d。
覆寫內建名稱是官方支援的做法,但官方提醒:days、hours 這類以時間命名的 profile,讀程式的人會直覺以為就是一天、一小時,改掉它比改 default、max 更容易造成誤會。要不同的數值,另取一個自訂名稱通常比較清楚;真的要覆寫,記得寫進專案文件。
行內物件:只用一次的設定
只有單一函式需要特殊壽命時,直接把物件傳給 cacheLife,不必寫進 next.config.ts:
import { cacheLife } from 'next/cache'
export default async function Page() {
'use cache'
cacheLife({
stale: 600,
revalidate: 1800,
expire: 43200,
})
return <p>inline: {new Date().toISOString()}</p>
}
行內物件一樣可以只寫部分屬性,沒寫的沿用 default;cacheLife({}) 傳空物件就等於 default。只寫 cacheLife({ revalidate: 7200 }) 時,expire 沿用 default 的不過期:
├ ○ /tests/nextjs-cachelife/inline 30m 12h
├ ○ /tests/nextjs-cachelife/inline-partial 2h 1y
default 的 expire 是 never,建置輸出的 Expire 欄顯示為 1y。
依條件設定不同壽命
同一個快取函式可以依資料狀況呼叫不同的 profile,只要每次執行只跑到一個 cacheLife。例如文章還沒發布時只快取幾分鐘,發布後快取一天:
// app/posts/[slug]/page.tsx
import { cacheLife } from 'next/cache'
async function getPost(slug: string) {
'use cache'
if (slug === 'draft') {
cacheLife('minutes')
return null
}
cacheLife('days')
return { slug, at: new Date().toISOString() }
}
export function generateStaticParams() {
return [{ slug: 'draft' }, { slug: 'hello' }]
}
export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const post = await getPost(slug)
return <p>{post ? `${post.slug} ${post.at}` : '尚未發布'}</p>
}
兩個路徑各自得到不同的壽命:
│ ├ ○ /tests/nextjs-cachelife/conditional/draft 1m 1h
│ └ ○ /tests/nextjs-cachelife/conditional/hello 1d 1w
壽命要從資料算出來(例如 CMS 欄位存了秒數)時,改用行內物件,例如 cacheLife({ revalidate: post.revalidateSeconds ?? 3600 })。
巢狀快取:以哪一層的 cacheLife 為準
快取元件裡用到另一個快取元件或函式時,外層的壽命取決於外層有沒有明確呼叫 cacheLife。
外層有寫 cacheLife:以外層為準,不論內層比較長或比較短。外層快取命中時,直接回傳包含內層資料的完整輸出。
import { cacheLife } from 'next/cache'
async function Widget() {
'use cache'
cacheLife('minutes')
return <p>widget: {new Date().toISOString()}</p>
}
export default async function Page() {
'use cache'
cacheLife('hours')
return (
<div>
<h1>Dashboard</h1>
<Widget />
</div>
)
}
外層沒寫 cacheLife:外層套用 default,內層較短的壽命會把外層縮短;內層較長則不會讓外層超過 default。同樣的結構,只改外層有沒有 cacheLife('hours') 與內層的 profile,建置輸出如下:
| 外層 | 內層 | 路由 Revalidate/Expire |
|---|---|---|
cacheLife('hours') | minutes | 1h/1d |
| 沒寫 | minutes | 1m/1h |
| 沒寫 | days | 15m/1w |
第三列的 revalidate 維持 default 的 15 分鐘,內層 days 的 1 天沒有把它拉長;expire 則從不過期縮短成內層的 1 週。外層沒寫 cacheLife 時,結果要追到每一層內層才算得出來,這也是官方建議每一層都明確寫的原因。
內層太短時會直接報錯
內層是短壽命快取(revalidate 為 0,或 expire 少於 5 分鐘,內建 profile 中只有 seconds),外層又沒寫 cacheLife 時,外層會被悄悄縮短成同樣的短壽命。為了避免這種誤設定,Next.js 在預先渲染時會丟出錯誤:
import { cacheLife } from 'next/cache'
async function ShortLivedWidget() {
'use cache'
cacheLife('seconds')
return <p>widget: {new Date().toISOString()}</p>
}
export default async function Page() {
'use cache'
// 外層沒有 cacheLife
return (
<div>
<h1>Dashboard</h1>
<ShortLivedWidget />
</div>
)
}
Error: Route "/tests/nextjs-cachelife/err-nested-short": A nested `"use cache"` with a short `expire` (under 5 minutes) is inside an outer `"use cache"` that has no `cacheLife()`. Add `cacheLife()` to the outer one to choose whether to prerender it with a longer `expire` or keep it dynamic with a short `expire`.
Learn more: https://nextjs.org/docs/messages/nested-use-cache-no-explicit-cachelife
這個內層元件也可能來自別的模組或第三方套件,看外層程式碼不一定看得出來。修正方式是在外層加上明確的 cacheLife:
- 外層要維持預先渲染:寫較長的壽命,例如
cacheLife('default')。 - 外層也要短壽命:明確寫短的 profile(例如
cacheLife('seconds')),並用<Suspense>包住這個元件提供載入中畫面。官方範例在這種情況改用'use cache: remote',因為 Serverless 環境預設的記憶體快取不會跨請求保留;自架伺服器用'use cache'可能就夠。
太短的快取不會被預先渲染
壽命太短的快取,Next.js 不會放進預先渲染的結果:
revalidate為 0,或expire少於 5 分鐘:不進預先渲染,成為請求時才解析的動態區塊。stale少於 30 秒:不進預先渲染,因為預先載入的內容在使用者點擊前就會過期。stale至少 30 秒但少於 5 分鐘:會進預先渲染,但不放進路由的 App Shell。
內建 profile 中只有 seconds 落在這些門檻內(expire 1 分鐘)。所以同一頁可以混合靜態與動態內容:長壽命的部分在建置時預先渲染,seconds 這類短壽命快取在請求時取得,外面用 <Suspense> 提供載入中畫面。動態區塊與靜態外殼的概念,可以參考〈Next.js PPR 教學:結合 SSG 快取速度與 SSR 即時資料的混合渲染解析〉,設定方式以 cacheComponents 為準。
發佈留言