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

Next

Next.js instant 用法:Cache Components 導覽即時驗證、instant = false 與 validationLevel

Next.js instant 用法:Cache Components 導覽即時驗證、instant = false 與 validationLevel 特色圖片

Next.js instant 是 Route Segment Config 的一個選項:在 page 或 layout 匯出 export const instant = true,Next.js 會在開發模式檢查「導覽到這個區段時,畫面能不能立即更新,而不必等外部資料」,有會阻塞導覽的程式碼就列出來。instant 只在開啟 cacheComponents 時有效,v16.3.0 起取代原本的 unstable_instant。Route Segment Config 的其他選項與舊選項的替代寫法,可以先看〈Next.js Route Segment Config 用法〉,本文只講 instant。範例在 Next.js 16.4.3、開啟 cacheComponents 與 partialPrefetching 的專案執行。

instant 的基本寫法

// app/shop/[slug]/page.tsx
export const instant = true

export default function Page() {
  return <div>...</div>
}

使用前要知道三件事:

  • 只在 next.config.ts 開啟 cacheComponents: true 時有效。沒開時使用,開發伺服器會回 500,錯誤訊息是 Route segment config "instant" requires `nextConfig.cacheComponents` to be enabled.
  • 只能放在 Server Component 模組。檔案開頭有 'use client' 時會直接編譯失敗(訊息見後面的「常見錯誤」)。
  • 開發模式不做 prefetch,所以 next dev 裡的導覽不一定像正式環境一樣快;驗證結果反映的是 next start(有 prefetch)時的行為。

可接受的值

官方文件列出的型別如下:

type InstantConfig =
  | true
  | false
  | {
      level?: 'warning'
    }
值意思
true讓這個區段接受驗證,等級跟著全域設定(預設只在開發模式驗證,錯誤顯示在 dev overlay)
false這個區段允許在導覽時阻塞,退出驗證
{ level: 'warning' }用物件寫法指定等級

level 目前只有 'warning' 一種:只在開發模式驗證,錯誤出現在 dev overlay,不影響 build。官方說明未來會加入在 build 時驗證的等級,在那之前除非啟用實驗性的驗證模式,不需要寫 level。下面兩種寫法目前效果相同:

export const instant = true
export const instant = {
  level: 'warning',
}

驗證抓的是什麼:共用 layout 以下的導覽

要看懂 instant 的錯誤,得先知道直接開啟頁面和站內導覽的差別。直接開啟時整頁從根節點渲染,任何一層的 <Suspense> 都能接住正在等待的元件;但從 /shop/shoes 點到 /shop/hats 這種用戶端導覽,只會重新渲染兩個路由共用的 layout 以下的部分,放在共用 layout(或更上層)的 <Suspense> fallback 在這次導覽用不到。

instant 會在路由中每一個共用 layout 的邊界做驗證,分別模擬頁面載入與各種導覽。下面這個例子,<Suspense> 放在 app/shop/layout.tsx:

// app/shop/layout.tsx
import Link from 'next/link'
import { Suspense } from 'react'

export default function ShopLayout({ children }: { children: React.ReactNode }) {
  return (
    <section>
      <nav>
        <Link href="/shop/shoes">shoes</Link> | <Link href="/shop/hats">hats</Link>
      </nav>
      <Suspense fallback={<p>Loading...</p>}>{children}</Suspense>
    </section>
  )
}
// app/shop/[slug]/page.tsx
import { connection } from 'next/server'

export const instant = true

export default async function Page(props: PageProps<'/shop/[slug]'>) {
  const { slug } = await props.params
  await connection()
  return <p>商品:{slug}({new Date().toISOString()})</p>
}

直接開 /shop/shoes 會正常回 200,因為 layout 的 <Suspense> 接住了頁面;但在 shoes 與 hats 之間導覽時,/shop layout 已經掛載,只有頁面重新渲染,await connection() 沒有任何 fallback 可用,導覽會卡住。開發伺服器在頁面載入後印出:

Error: Route "/shop/[slug]": Next.js encountered uncached data during prerendering or a navigation.

`fetch(...)` or `connection()` accessed outside of `<Suspense>` prevents the route from being prerendered or the navigation from being instant, leading to a slower user experience.

Ways to fix this:
  - [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
  - [cache] Cache the data access with `"use cache"` (does not apply to `connection()`)
  - [block] Set `export const instant = false` to allow a blocking route

Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic
    at Page (app\shop\[slug]\page.tsx:7:19)
  ...
  [cause]: Instant Validation:
      at instant (app\shop\[slug]\page.tsx:3:24)

錯誤會指出阻塞導覽的那一行,[cause] 指回 export const instant = true。瀏覽器左下角的 Next.js 指示器同時顯示「1 Insight」,點開後可以看到同一個錯誤與修法選項:

點開 Next.js 指示器的 1 Insight 後,面板標示 Instant 與 Server,標題為 Next.js encountered uncached data during a navigation,並標出 await connection() 那一行

Next.js 16.4.3 next dev、無頭 Chrome 156 直接開啟商品頁後點開指示器的畫面(測試專案的路由位於 /tests/nextjs-instant/ 底下)。

這時執行 next build 仍然會成功,路由顯示為 ◐(Partial Prerender):'warning' 等級不影響 build。

修法:把 Suspense 放進頁面,或快取資料

官方建議的修法通常是用 use cache 快取資料,或包進 <Suspense>。這個例子用了 connection()(每次請求都要動態取得,use cache 不適用),所以把 <Suspense> 移到頁面裡、也就是共用 layout 以下:

// app/shop/[slug]/page.tsx
import { Suspense } from 'react'
import { connection } from 'next/server'

export const instant = true

export default function Page(props: PageProps<'/shop/[slug]'>) {
  return (
    <Suspense fallback={<p>Loading product...</p>}>
      <Product params={props.params} />
    </Suspense>
  )
}

async function Product({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  await connection()
  return <p>商品:{slug}({new Date().toISOString()})</p>
}

layout 拿掉原本的 <Suspense>、改成直接放 {children} 後,開啟 /shop/shoes、/shop/hats 都回 200,開發伺服器不再出現驗證錯誤。商品資料若是不常變動的資料庫查詢,也可以改用 'use cache' 快取,詳見〈Next.js use cache 指令用法〉。

instant = false:讓上層 layout 允許阻塞

false 表示這個區段在導覽時可以阻塞。典型用法是:共用 layout 本身沒辦法立即載入(例如要讀 cookie),但仍希望 layout 底下各分頁之間的切換是即時的:

// app/tabs/layout.tsx
import Link from 'next/link'
import { cookies } from 'next/headers'

export const instant = false

export default async function TabsLayout({ children }: { children: React.ReactNode }) {
  const theme = (await cookies()).get('theme')?.value ?? 'light'
  return (
    <section>
      <p>theme: {theme}</p>
      <nav>
        <Link href="/tabs/profile">profile</Link> | <Link href="/tabs/billing">billing</Link>
      </nav>
      {children}
    </section>
  )
}
// app/tabs/[tab]/page.tsx
import { Suspense } from 'react'

export const instant = true

export default function Page(props: PageProps<'/tabs/[tab]'>) {
  return (
    <Suspense fallback={<p>Loading tab...</p>}>
      <Tab params={props.params} />
    </Suspense>
  )
}

async function Tab({ params }: { params: Promise<{ tab: string }> }) {
  const { tab } = await params
  return <h2>{tab}</h2>
}

從外部導覽進任一分頁時允許在 layout 阻塞;分頁之間的導覽則照樣驗證是否即時。上面這組檔案開啟 /tabs/profile、/tabs/billing 都回 200,沒有驗證錯誤。

把 layout 的 export const instant = false 拿掉,開發伺服器就會報錯:

Error: Route "/tabs/[tab]": Next.js encountered runtime data during prerendering.

`cookies()`, `headers()`, `params`, or `searchParams` accessed outside of `<Suspense>` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.

不需要因為上層做了阻塞的事,就替每個祖先都加 false:上層的 instant = true 不會強迫子孫驗證,祖先不設定也沒關係。只有在「較深的頁面設為即時,而導覽會經過一個阻塞的祖先」時才需要 false。

instant = false 也會關掉 static shell 驗證

Cache Components 另外會檢查每個頁面在 prerender 時能產生非空的 static shell。要讓某個路由退出這項檢查,路由樹中最上層的 instant 要設成 false;在 static shell 檢查上,較高層的 false 優先於較深層的 true。

上面的 tabs 範例正好是這種情況:layout 在 <Suspense> 外讀 cookies(),因為 layout 設了 instant = false,next build 成功;拿掉這一行再 build,就會停在這個路由:

Error: Route "/tabs/[tab]": Next.js encountered uncached or runtime data during prerendering.
...
Error occurred prerendering page "/tabs/[tab]". Read more: https://nextjs.org/docs/messages/prerender-error
Export encountered an error on /tabs/[tab]/page: /tabs/[tab], exiting the build.

在 root layout 設 false 會關掉整個 app 的 static shell 驗證。官方建議把 false 放得越低越好,只蓋住要退出的路由,其他頁面才會繼續被驗證。

validationLevel:全域預設驗證範圍

不寫 instant 的頁面也會被驗證:Cache Components 的預設 validationLevel 是 'warning',開發模式會隱含驗證每一個 Page 與 Default 區段。想改成「只驗證有明確匯出 instant 的區段」,在 next.config.ts 設定 experimental.instantInsights.validationLevel:

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

const nextConfig: NextConfig = {
  cacheComponents: true,
  experimental: {
    instantInsights: {
      validationLevel: 'manual-warning',
    },
  },
}

export default nextConfig
等級驗證範圍
'warning'(預設)每個 Page 與 Default 區段都隱含以 warning 等級驗證(只在開發模式)
'manual-warning'只驗證有明確匯出 instant 的區段(只在開發模式)

改成 'manual-warning' 後,一個沒有匯出 instant、在頁面裡直接 await connection() 的路由不再出現錯誤;有 export const instant = true 的 /shop/[slug] 仍然會報錯。開發伺服器啟動時也會列出 Experiments (use with caution): · instantInsights。

補充幾點官方說明:

  • instant = false 會讓該區段完全退出驗證。
  • 這是實驗性功能,框架預設等級未來可能調高,而且不算 breaking change;要固定行為就明確寫出 validationLevel。
  • 框架自動產生的錯誤路由(/_global-error、/_not-found)不在隱含驗證範圍,要驗證得明確匯出 instant。
  • 開啟 Partial Prefetching 時,在 <Suspense> 外讀取 params、searchParams 會出現 URL data 的 insight,同樣只在開發模式出現、不擋 build,也可以用 instant = false 讓路由退出驗證。

instant 和 ensureStatic 的差別

兩者都是 Cache Components 專用的設定,但檢查的東西不同:

選項檢查什麼
instant導覽時畫面能不能立即顯示
ensureStatic指定的伺服器輸出必須是靜態,不能每次請求才渲染

一個完全靜態的路由仍然可能阻塞導覽,例如 Client Component 在瀏覽器端才載入資料。

檢查載入畫面:Navigation Inspector

開啟 Cache Components 後,Next.js DevTools 有 Navigation Inspector。打開後開啟 Pause on navigations:

  • 重新整理頁面,會凍結路由的初始 static UI(動態資料串流進來之前的樣子)。
  • 點連結,會凍結目的路由經 prefetch 的 UI。

畫面凍結時按 Resume 讓這次導覽完成;開關會保持開啟,下一次重新整理或點連結一樣會暫停,檢查完記得關掉。

DevTools 是靠 next-instant-navigation-testing 這個 cookie 來凍結畫面。cookie 只分網域、不分連接埠,同時在 localhost 跑多個專案時會互相影響,切換專案時要清掉這個 cookie 或關閉 Navigation Inspector。官方表示這會在功能穩定時修正。

用 Playwright 測試

@next/playwright 套件匯出 instant() 輔助函式,在 callback 執行期間擋住動態內容,讓斷言只針對導覽當下就有的 UI。開發模式下自動可用;要對 production build 測試,需在測試用的 build 開啟 experimental.exposeTestingApiInProductionBuild。

使用方式是從 @next/playwright 匯入 instant,完整範例見官方 Instant Navigation 指南的 e2e 測試段落。

常見錯誤

在 Client Component 匯出 instant:

'use client'

export const instant = true

開發伺服器編譯時報錯,該頁回 500:

Error: Next.js can't recognize the exported `instant` field in route. "instant" is a route segment config and can only be used when the segment is a Server Component module. Remove the "use client" directive to use this API.

要用 instant 的頁面不能加 'use client';互動的部分拆成獨立的 Client Component,再由 Server Component 的頁面引入。

參考資料與延伸閱讀

發佈留言