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

Next

Next.js Route Segment Config 用法:page、layout、route 匯出設定與 Next.js 16 現行選項

Next.js Route Segment Config 用法:page、layout、route 匯出設定與 Next.js 16 現行選項 特色圖片

Next.js 的 Route Segment Config(路由區段設定)是在 page、layout 或 Route Handler(route.ts)裡直接 export 特定名稱的變數,用來調整這個路由區段的行為,例如 export const maxDuration = 5。Next.js 16 的選項和舊版差很多:開啟 Cache Components(cacheComponents: true)之後,dynamic、revalidate、fetchCache、dynamicParams 都不能再用,experimental_ppr 已移除,另外多了 ensureStatic、instant、prefetch 這幾個 Cache Components 專用選項。本文以 Next.js 16(範例在 16.4.3、開啟 cacheComponents 與 partialPrefetching 的專案執行)整理現行選項、各自能放在哪種檔案,以及舊選項的替代寫法。

Route Segment Config 怎麼寫

在 page.tsx、layout.tsx 或 route.ts 的模組頂層,用官方規定的名稱 export const,Next.js 會讀取這個值:

// app/report/page.tsx
export const maxDuration = 5

export default function Page() {
  return <p>maxDuration = 5</p>
}

Route Handler 的寫法一樣,跟 GET 等方法並列:

// app/api/report/route.ts
export const maxDuration = 5

export async function GET() {
  return Response.json({ ok: true })
}

opengraph-image、twitter-image 這類 metadata 圖檔是特殊的 Route Handler,也可以使用和 page、layout 相同的 Route Segment Config。

Next.js 16 現行選項一覽

官方 Route Segment Config 頁面的表格列出 dynamicParams、runtime、preferredRegion、maxDuration 四項,並註明開啟 Cache Components 時 page 與 layout 另外支援 ensureStatic;同一頁的子頁面還有 instant 與 prefetch,兩者同樣只在開啟 cacheComponents 時有效。

選項可用的值預設備註
dynamicParamstrue、falsetrue開啟 Cache Components 時不能用
runtime'nodejs'、'edge'(已棄用)'nodejs'開啟 Cache Components 時要整個移除
preferredRegion'auto'、'global'、'home'、string、string[]'auto'已棄用
maxDurationnumber(秒)由部署平台決定page、layout、route 都能用
ensureStatic'auto'、'shell'、'prefetch'、'navigation'、false'auto'Cache Components 專用,page、layout
instanttrue、false、{ level: 'warning' }—Cache Components 專用,page、layout
prefetch'auto'、'partial'、'force-disabled''auto'Cache Components 專用,page、layout

dynamicParams:沒列在 generateStaticParams 的參數

dynamicParams 決定動態路由遇到 generateStaticParams 沒有回傳的參數時怎麼處理:true(預設)在請求時產生頁面,false 回 404。它取代 pages 目錄 getStaticPaths 的 fallback 選項。

這個選項只能在沒有開啟 Cache Components 的專案使用:

// app/posts/[id]/page.tsx(未開啟 cacheComponents)
export const dynamicParams = false

export function generateStaticParams() {
  return [{ id: '1' }, { id: '2' }]
}

export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  return <p>id = {id}</p>
}
GET /posts/1 200
GET /posts/3 404

開啟 cacheComponents 後,同一個檔案會讓 build 失敗:

./app/posts/[id]/page.tsx:1:14
Error: Route segment config "dynamicParams" is not compatible with `nextConfig.cacheComponents`. Please remove it.

官方遷移文件的替代寫法是刪掉 dynamicParams,在頁面查無資料時呼叫 notFound():

// app/posts/[id]/page.tsx(開啟 cacheComponents)
import { notFound } from 'next/navigation'

const posts: Record<string, string> = { '1': '第一篇', '2': '第二篇' }

export function generateStaticParams() {
  return [{ id: '1' }, { id: '2' }]
}

export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  const title = posts[id]
  if (!title) notFound()
  return <p>id = {id}:{title}</p>
}

要注意狀態碼:官方 notFound() 文件說明,回應開始串流之後才呼叫 notFound(),狀態碼會維持 200。在開啟 partialPrefetching 的專案中,上面這頁用 next start 請求沒列在 generateStaticParams 的 /posts/3,畫面是 404 頁,狀態碼卻是 200:

GET /posts/3 200(cache-control: private, no-cache, no-store, max-age=0, must-revalidate)

同一頁再加上 export const ensureStatic = 'navigation',第一次請求就會等完整的靜態頁產生,notFound() 在串流開始前執行,回到 404:

GET /posts/1 200(x-nextjs-cache: HIT)
GET /posts/3 404(x-nextjs-cache: MISS)
GET /posts/3 404(x-nextjs-cache: HIT)

notFound() 與狀態碼的細節見 Next.js not-found.js 用法,動態路由與 generateStaticParams 見 Next.js 動態路由 Dynamic Segments 用法。

maxDuration:伺服器端執行時間上限

maxDuration 以秒為單位,設定這個路由區段伺服器端邏輯的最長執行時間,layout、page、route 都能用。部署平台會從 Next.js 的 build 輸出讀取這個值來套用執行時間限制,沒設定時的預設值也由部署平台決定。

用了 Server Actions 的頁面,在 page 層設定 maxDuration,會改變該頁所有 Server Actions 的預設逾時。

runtime 與 preferredRegion

runtime 選擇渲染路由用的 JavaScript runtime,預設 'nodejs','edge' 已棄用,官方建議直接移除 runtime 匯出。開啟 Cache Components 時連 runtime = 'nodejs' 也要拿掉,否則 build 失敗:

Error: Route segment config "runtime" is not compatible with `nextConfig.cacheComponents`. Please remove it.

需要在請求前做 Edge 層級的處理時,官方遷移文件建議改用 Proxy,寫法見 Next.js proxy.js 用法。

preferredRegion 指定路由偏好的部署區域,值直接交給部署平台,同樣已棄用,官方要求從路由檔移除。

Cache Components 專用:ensureStatic、instant、prefetch

這三個選項只能放在 page 或 layout,也不能用在 Client Component;沒開啟 cacheComponents 時不會生效,其中 ensureStatic 會直接讓 build 失敗。next dev 不會擋下這個設定,頁面照常回 200,錯誤要到 next build 收集頁面資料時才出現(以根目錄 app/page.js 為例):

> Build error occurred
Error: Route "/page" cannot use `export const ensureStatic = ...` without enabling `cacheComponents`.

下面只做簡介。

ensureStatic:要求輸出必須是靜態

ensureStatic 從 v16.4.0 加入,要求選定的伺服器端輸出在預先產生時完成,不能每次請求才渲染:'shell' 要求 App Shell 靜態,'prefetch' 再加上每個連結的 prefetch,'navigation' 要求整個伺服器端渲染的路由都是靜態。子區段可以設更嚴格的等級,設比父層寬鬆的等級會讓 build 失敗。

'navigation' 會在 next dev 與 next build 驗證。頁面讀 cookies() 時,即使包在 <Suspense> 裡也不通過:

// app/settings/page.tsx
import { cookies } from 'next/headers'
import { Suspense } from 'react'

export const ensureStatic = 'navigation'

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

export default function Page() {
  return (
    <Suspense fallback={<p>載入中…</p>}>
      <Theme />
    </Suspense>
  )
}
Error: Route "/settings": Next.js encountered uncached or runtime data on a route that must be fully static.

This route is configured to be fully static, but some data requires rendering at request time.

instant:檢查導覽能不能立即顯示畫面

instant = true 讓 Next.js 檢查導覽到這個區段時,畫面能不能立即更新而不必等外部資料;false 表示允許阻塞。預設等級 'warning' 只在開發模式檢查,錯誤顯示在 dev overlay,不影響 build。v16.3.0 起取代 unstable_instant。沒開啟 cacheComponents 時使用,開發伺服器會回 500:

Error: Route segment config "instant" requires `nextConfig.cacheComponents` to be enabled.

prefetch:控制區段的 prefetch 方式

prefetch = 'partial' 讓單一區段先採用 Partial Prefetching,不必開全域的 partialPrefetching;'force-disabled' 讓這個區段完全不被 prefetch,例如很少有人進入的登入後頁面。'auto' 是預設值,官方建議不要明寫。v16.3.0 起取代 unstable_prefetch。

已移除或不相容的舊選項

v16.0.0 起,開啟 Cache Components 時 dynamic、dynamicParams、revalidate、fetchCache 都被移除,匯出這些變數 build 會失敗,錯誤訊息格式相同:

Error: Route segment config "dynamic" is not compatible with `nextConfig.cacheComponents`. Please remove it.
Error: Route segment config "revalidate" is not compatible with `nextConfig.cacheComponents`. Please remove it.

沒開啟 Cache Components 的專案仍可使用,官方說明移到「Caching and Revalidating (Previous Model)」頁面。依官方遷移文件,對應的改法如下:

舊寫法開啟 Cache Components 後的做法
dynamic = 'force-dynamic'直接刪除;未快取的資料與 Request-time API 本來就在請求時執行
dynamic = 'force-static'刪除,用 use cache 加 cacheLife 明確快取資料
dynamic = 'error'刪除,需要的資料包進 use cache;要強制整頁靜態可加 ensureStatic = 'navigation'
revalidate = 3600改用 use cache 加 cacheLife
fetchCache刪除,要快取的資料放進 use cache 範圍,不快取的留在外面
dynamicParams = false刪除,查無資料時呼叫 notFound()
runtime刪除(含 'nodejs')
experimental_ppr = truev16.0.0 已移除,改開 cacheComponents,官方提供 codemod

revalidate = 3600 的替代寫法:

// app/report/page.tsx
import { cacheLife } from 'next/cache'

export default async function Page() {
  'use cache'
  cacheLife('hours')
  const time = new Date().toISOString()
  return <p>產生時間:{time}</p>
}

cacheLife('hours') 的 revalidate 是 1 小時、expire 是 1 天,next build 的路由表會顯示:

Route (app)                Revalidate  Expire
├ ○ /report                        1h      1d

use cache 與 cacheLife 的完整用法見 Next.js use cache 指令用法,Partial Prerendering 從實驗旗標併入 Cache Components 的背景見 Next.js PPR 教學。

參考資料與延伸閱讀

發佈留言