NNext.js 中文网 GitHub

在适配器中实现 PPR

使用 fallback 输出和缓存钩子在适配器中实现 Partial Prerendering 支持。

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

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

1. 在构建时播种外壳 + postponed 状态#

my-adapter.ts
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. 恢复的渲染流(在使用 postponed 状态调用 handler 后生成)
text
客户端
  | GET /ppr-route
  v
适配器路由器
  |
  |-- 读取缓存的外壳 + postponedState ---> 平台缓存
  |<------------- 缓存命中 -----------------|
  |
  |-- 创建 responseStream = concat(shellStream, resumedStream)
  |
  |-- 开始写入 shellStream ------------> 客户端(首批字节)
  |
  |-- 调用 handler(req, res, { requestMeta: { postponed } })
  |   -------------------------------------> 入口点(handler)
  |   <------------------------------------- 恢复的块/缓存条目
  |
  |-- 将恢复的块追加到 resumedStream
  |
  '-- 客户端收到一个 HTTP 响应:
      [外壳字节........][恢复字节........]

3. 使用 requestMeta.onCacheEntryV2 更新缓存#

requestMeta.onCacheEntryV2 在查找或生成响应缓存条目时调用。可用它持久化更新后的外壳/postponed 数据。

[!NOTE]

  • requestMeta.onCacheEntry 仍然可用,但已弃用。
  • 推荐使用 requestMeta.onCacheEntryV2。
  • 如果你的适配器使用内部的 onCacheCallback 抽象,请将其连接到 requestMeta.onCacheEntryV2。
my-adapter.ts
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,
        })
      }

      // 仅当你的适配器已自行写入响应时才返回 true。
      return false
    },
  },
})
text
入口点(handler)
  | onCacheEntryV2(cacheEntry, { url })
  v
requestMeta.onCacheEntryV2 回调
  |
  |-- 如果是 APP_PAGE ---> 持久化 html + postponedState + headers ---> 平台缓存
  |
  '-- 返回 false:继续正常的 Next.js 响应流程
      返回 true:适配器已处理响应(短路)
Next.js 中文网