Next.js connection 是 next/server 提供的函式,await connection() 之後的程式碼只會在收到實際使用者請求時執行,不會在預先渲染(prerender)時執行。它用在元件沒有呼叫 cookies()、headers() 這類 Request-time API,卻需要每次請求產生不同結果的情況,例如 Math.random()、new Date(),或同步資料庫驅動的查詢。本文以 Next.js 16.4.3 專案的範例說明寫法、在 Cache Components 下要搭配 <Suspense> 的原因、不能放進 "use cache" 的限制,以及它和 io() 的差別。
connection 的基本寫法
官方文件的範例:
// app/page.tsx
import { connection } from 'next/server'
export default async function Page() {
await connection() // prerender 停在這裡
// 以下程式碼只在請求時執行
const rand = Math.random()
return <span>{rand}</span>
}
| 項目 | 說明 |
|---|---|
| 型別 | function connection(): Promise<void> |
| 參數 | 無 |
| 回傳值 | void 的 Promise,只用來 await,沒有值可以取用 |
| 匯入位置 | next/server |
next/server 的型別宣告註解寫的行為是:prerender 期間這個 Promise 永遠不會 resolve,實際請求的渲染期間則立即 resolve。所以 await connection() 之後的程式碼不會進到 prerender 的輸出。
官方文件也提醒,只有「需要動態渲染、又沒有用到常見 Request-time API」時才需要它。已經呼叫 cookies() 或 headers() 的元件,本身就會在請求時渲染,不必再加 connection()。
Cache Components 下要包在 Suspense 裡
開啟 cacheComponents 的專案,直接把上面的官方範例放在 page 頂層,next build 會失敗:
Error: Route "/tests/nextjs-connection/top": Next.js encountered uncached or runtime data during prerendering.
`fetch(...)`, `cookies()`, `headers()`, `params`, `searchParams`, or `connection()` accessed outside of `<Suspense>` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [cache] For uncached data (`fetch`, database calls): cache the access with `"use cache"` (does not apply to `connection()`)
- [block] Set `export const instant = false` to allow a blocking route
錯誤訊息對應的官方說明頁指出,"use cache" 這個修法不適用於 connection():connection() 的用意就是讓包住的子樹每次請求都重新渲染,快取起來就失去意義,要改用 <Suspense>。寫法是把 connection() 移到被 <Suspense> 包住的子元件裡:
// app/page.tsx
import { Suspense } from 'react'
import { connection } from 'next/server'
export default function Page() {
return (
<>
<h1>static shell</h1>
<Suspense fallback={<p>Loading...</p>}>
<RandomNumber />
</Suspense>
</>
)
}
async function RandomNumber() {
await connection()
const rand = Math.random()
const now = new Date().toISOString()
return <p>rand={rand} now={now}</p>
}
這樣 next build 會通過,路由標記為 ◐(Partial Prerender:預先產生靜態 HTML,動態內容在請求時串流)。建置產出的 HTML 只有 static shell 標題與 Loading... fallback,沒有亂數;以 next start 啟動後連續請求兩次,rand 與 now 每次都不同:
rand=0.10931475476803998 now=2026-11-03T07:18:39.924Z
rand=0.8369692139583824 now=2026-11-03T07:18:40.049Z

Next.js 16.4.3 next start、無頭 Chrome 156 開啟頁面的畫面:標題來自靜態外殼,rand 與 now 在請求時產生。
沒有開啟 Cache Components 的專案,官方開頭的頂層寫法可以直接使用,next dev 下每次請求都會得到不同的數字。
Math.random 與 new Date 為什麼需要 connection
開啟 Cache Components 時,Server Component 在 <Suspense> 外直接呼叫 Math.random(),next build 會停在這個錯誤:
Error: Route "/tests/nextjs-connection/random-only": Next.js encountered the unstable value `Math.random()` while prerendering.
This value can change between renders, so it must be either prerendered or computed later.
Ways to fix this:
- [dynamic] Render at request time by adding a dynamic data access (e.g. `await connection()`) before this call
- [cache] Prerender and cache the value with `"use cache"`
- [client] Render the value on the client with `"use client"`
官方錯誤說明頁的解釋是:建置時算出的值和執行時不同,Next.js 不能把無法預測的值直接寫進 prerender 的 HTML,所以要選一種做法:
| 做法 | 適用情境 |
|---|---|
await connection() 後再取值,外層包 <Suspense> | 每次請求都需要不同的值,例如一次性 nonce、A/B 測試分組 |
用 "use cache" 快取這個值 | 值可以固定,所有訪客共用 |
| 改在 Client Component 產生 | 值在瀏覽器端產生即可 |
Date.now() 與 crypto.randomUUID() 有對應的錯誤說明頁,處理方式相同。官方也提醒,<Suspense> 的 fallback、loading.js、error.js、not-found.js 都屬於 prerender 的外殼,在這些地方呼叫 Math.random() 或 Date.now() 一樣會出現這個錯誤;<Suspense> 邊界要盡量貼近讀取亂數的元件。
同步資料庫驅動:查詢前先呼叫 connection
同步資料庫驅動的查詢會在 prerender 時直接完成,結果被寫進建置產物。官方範例以 better-sqlite3 示範:沒有用到 Request-time API 時,在查詢前呼叫 connection(),呼叫這個函式的元件就會連同其輸出一起排除在 prerender 之外。下面改用 Node.js 內建的 node:sqlite(同步 API)寫成相同結構,每次查詢把計數加 1:
// app/lib/data.js
import { connection } from 'next/server'
import { DatabaseSync } from 'node:sqlite'
const db = new DatabaseSync(':memory:')
db.exec('CREATE TABLE counters (name TEXT PRIMARY KEY, value INTEGER)')
db.prepare('INSERT INTO counters VALUES (?, ?)').run('visitors', 0)
export async function getVisitorCount() {
await connection()
db.prepare('UPDATE counters SET value = value + 1 WHERE name = ?').run('visitors')
return db.prepare('SELECT value FROM counters WHERE name = ?').get('visitors')
}
// app/page.tsx
import { Suspense } from 'react'
import { getVisitorCount } from './lib/data'
export default function Page() {
return (
<Suspense fallback={<p>Loading...</p>}>
<Visitors />
</Suspense>
)
}
async function Visitors() {
const row = await getVisitorCount()
return <p>visitors={row.value}</p>
}
建置後的 HTML 只有 Loading...,next start 後第一次請求顯示 visitors=1、第二次 visitors=2,代表查詢發生在每次請求。Node.js v22 執行 node:sqlite 時會印出 ExperimentalWarning: SQLite is an experimental feature。
不能在 use cache 函式內呼叫
connection() 依賴實際請求,不能放在使用 "use cache" 的函式裡:
async function Cached() {
'use cache'
await connection() // 建置失敗
return <p>{Math.random()}</p>
}
next build 的錯誤:
Error: Route "/tests/nextjs-connection/cached": `connection()` can't be called inside `"use cache"` because cached functions may run during prerendering, without an incoming request. Call it outside the cached function.
修法是把 connection() 移到快取函式外面呼叫,只把需要的值當參數傳進快取函式。'use cache: private' 同樣不允許呼叫 connection()。快取函式的寫法可參考 Next.js use cache 指令用法。
connection 與 io 的差別
Next.js 16.3.0 在 next/cache 新增 io()。官方 connection 頁建議:開啟 Cache Components 時,要把內容排除在靜態外殼之外,優先用 io(),只有確實要等實際使用者請求時才用 connection()。
| 比較 | connection() | io() |
|---|---|---|
| 匯入位置 | next/server | next/cache |
| prerender 期間 | 暫停,等到完整的使用者導覽送到伺服器 | 暫停,像一般非同步函式 |
"use cache" 內 | 不能呼叫 | 立即 resolve(no-op),值被收進靜態外殼 |
| Client Component | 不適用 | 可搭配 React use(io()) |
| prefetch | 會擋住 prefetch | 之後的程式碼可包進 "use cache",在用戶端 prefetch 與快取 |
| 未開啟 Cache Components | 用在需要動態渲染、又沒有 Request-time API 的元件 | 立即 resolve |
io() 的寫法與 connection() 相同,換掉匯入即可:
import { io } from 'next/cache'
async function CurrentTime() {
await io()
return <p>{new Date().toISOString()}</p>
}
這段在開啟 Cache Components 的專案 next build 後同樣是 ◐,建置產出的 HTML 只有 Loading...,每次請求時間都不同。
connection 取代 unstable_noStore
connection 取代了 unstable_noStore。unstable_noStore 在官方文件已標為 Legacy,版本歷史寫 v15.0.0 起改用 connection。舊專案還在用 noStore() 排除 prerender 的地方,可以改成 await connection()。
版本歷史
| 版本 | 變更 |
|---|---|
v15.0.0-RC | 推出 connection |
v15.0.0 | connection 成為穩定 API |
v16.3.0 | 新增 io()(next/cache) |
同樣在回應階段處理工作的函式,可以參考 Next.js after 用法。
參考資料與延伸閱讀
- Next.js Docs: connection
- Next.js Docs: io
- Next.js Docs: unstable_noStore
- Next.js Docs: Math.random() while prerendering
- Next.js Docs: Uncached or runtime data during prerendering
- Next.js Docs: Cannot access request data inside use cache
- Node.js Docs: SQLite
- Next.js PPR 教學:結合 SSG 快取速度與 SSR 即時資料的混合渲染解析
- Next.js use cache 指令用法:函式、元件與檔案層級快取、cacheLife 與 cacheTag
- Next.js use cache: private 指令用法:在快取函式內讀取 cookies 與 headers
- Next.js after 用法:回應送出後執行 log、cookies 與 headers 限制、waitUntil 與部署支援
發佈留言