N Next.js 中文
原文 ↗

在适配器中实现 PPR

使用回退输出和缓存钩子在适配器中实现部分预渲染支持。

更新于 2026-03-30Next.js 16.4.6

对于部分预渲染的应用路由,onBuildComplete 提供了用于播种和恢复 PPR 所需的数据:

  • outputs.prerenders[].fallback.filePath:生成的回退外壳的路径(例如 HTML)
  • outputs.prerenders[].fallback.postponedState:用于恢复渲染的序列化推迟状态

1. 在构建时播种外壳 + 推迟状态

my-adapter.tsts
import { readFile } from 'node:fs/promises'

async function seedPprEntries(outputs: AdapterOutputs) {
  for (const prerender of outputs.prerenders) {
    const fallback = prerender.fallback
    if (!fallback?.filePath || !fallback.postponedState) continue

    const shell = await readFile(fallback.filePath, 'utf8')
    await platformCache.set(prerender.pathname, {
      shell,
      postponedState: fallback.postponedState,
      initialHeaders: fallback.initialHeaders,
      initialStatus: fallback.initialStatus,
      initialRevalidate: fallback.initialRevalidate,
      initialExpiration: fallback.initialExpiration,
    })
  }
}

2. 运行时流程:提供缓存的外壳并在后台恢复

在请求时,你可以流式渲染单个响应,它是以下内容的拼接:

  1. 缓存的 HTML 外壳流
  2. 恢复渲染流(在使用推迟状态调用 handler 后生成)
Client
  | GET /ppr-route
  v
Adapter Router
  |
  |-- read cached shell + postponedState ---> Platform Cache
  |<------------- cache hit -----------------|
  |
  |-- create responseStream = concat(shellStream, resumedStream)
  |
  |-- start piping shellStream ------------> Client (first bytes)
  |
  |-- invoke handler(req, res, { requestMeta: { postponed } })
  |   -------------------------------------> Entrypoint (handler)
  |   <------------------------------------- resumed chunks/cache entry
  |
  |-- append resumed chunks to resumedStream
  |
  '-- client receives one HTTP response:
      [shell bytes........][resumed bytes........]

3. 使用 requestMeta.onCacheEntryV2 更新缓存

当查找或生成响应缓存条目时会调用 requestMeta.onCacheEntryV2。用它来持久化更新后的外壳/推迟数据。

注意:

  • requestMeta.onCacheEntry 仍然可用,但已弃用。
  • 优先使用 requestMeta.onCacheEntryV2。
  • 如果你的适配器使用内部的 onCacheCallback 抽象,请将其连接到 requestMeta.onCacheEntryV2。
my-adapter.tsts
await handler(req, res, {
  waitUntil,
  requestMeta: {
    postponed: cachedPprEntry?.postponedState,
    onCacheEntryV2: async (cacheEntry, meta) => {
      if (cacheEntry.value?.kind === 'APP_PAGE') {
        const html =
          cacheEntry.value.html &&
          typeof cacheEntry.value.html.toUnchunkedString === 'function'
            ? cacheEntry.value.html.toUnchunkedString()
            : null

        await platformCache.set(meta.url || req.url || '/', {
          shell: html,
          postponedState: cacheEntry.value.postponed,
          headers: cacheEntry.value.headers,
          status: cacheEntry.value.status,
          cacheControl: cacheEntry.cacheControl,
        })
      }

      // Return true only if your adapter already wrote the response itself.
      return false
    },
  },
})
Entrypoint (handler)
  | onCacheEntryV2(cacheEntry, { url })
  v
requestMeta.onCacheEntryV2 callback
  |
  |-- if APP_PAGE ---> persist html + postponedState + headers ---> Platform Cache
  |
  '-- return false: continue normal Next.js response flow
      return true:  adapter already handled response (short-circuit)