N Next.js 中文
原文 ↗

connection

connection 函数的 API 参考。

更新于 2026-11-06Next.js 16.4.6

connection() 函数允许你指示渲染在继续之前应等待传入的用户请求。

当组件不使用 cookies 或 headers 等请求时 API,但仍需要针对每个请求产生不同输出(例如 Math.random() 或 new Date())时,它会很有用。

TypeScript

app/page.tsxts
import { connection } from 'next/server'

export default async function Page() {
  await connection() // prerendering stops here
  // the following code only runs at request time
  const rand = Math.random()
  return <span>{rand}</span>
}

JavaScript

app/page.jsjsx
import { connection } from 'next/server'

export default async function Page() {
  await connection() // prerendering stops here
  // the following code only runs at request time
  const rand = Math.random()
  return <span>{rand}</span>
}

示例

同步数据库驱动

来自 better-sqlite3 等同步数据库驱动的查询会在预渲染期间完成。如果你尚未使用请求时 API,请在查询前调用 connection(),以将其排除在预渲染之外:

TypeScript

app/lib/data.tsts
import { connection } from 'next/server'
import Database from 'better-sqlite3'

const db = new Database('app.db')

export async function getVisitorCount() {
  await connection()
  return db.prepare('SELECT value FROM counters WHERE name = ?').get('visitors')
}

JavaScript

app/lib/data.jsjs
import { connection } from 'next/server'
import Database from 'better-sqlite3'

const db = new Database('app.db')

export async function getVisitorCount() {
  await connection()
  return db.prepare('SELECT value FROM counters WHERE name = ?').get('visitors')
}

现在,任何调用 getVisitorCount() 的组件都会连同其其余输出一起被排除在预渲染之外。

参考

类型

function connection(): Promise<void>

参数

  • 该函数不接受任何参数。

返回值

  • 该函数返回一个 void Promise。不应使用其返回值。

须知

  • connection 取代了 unstable_noStore,以更好地契合 Next.js 的未来。
  • 仅当需要动态渲染且未使用常见的请求时 API 时,才需要该函数。
  • 使用缓存组件时,请将调用 connection() 的组件放在 <Suspense> 边界内,可以直接放置,也可以通过诸如 loading.js 文件之类的祖先放置。最近边界的回退内容会被预渲染到静态外壳中,而 connection() 之后的代码会在请求时运行。如果没有边界,导航到该路由时会阻塞,而不是即时完成。
  • 使用缓存组件时,若要从静态外壳中排除内容,请优先使用 io()。它的工作方式相同,并且也可以在 "use cache" 作用域内调用,在那里它会立即解析。仅当渲染需要等待真实用户请求时,才使用 connection()。

版本历史

版本 变更
v15.0.0 connection 已稳定。
v15.0.0-RC connection 已引入。