如何结合 `renderToPipeableStream` 与 Apollo 实现 HTML 流式输出?

解读

国内大厂(阿里、字节、美团、拼多多)在做「首字节时间(TTFB)优化」时,普遍把 SSR 从“一次性 renderToString”升级为“渐进式流式渲染”。
React 18 提供的 renderToPipeableStream 可以把组件树拆成多段 HTML 往浏览器“边渲染边吐”,Apollo Client 作为数据层必须解决两个核心矛盾:

  1. 服务端要先拉完“关键查询”再开始吐外壳,否则浏览器拿到 HTML 时数据是空的;
  2. 拉完关键数据后,还要把「序列化后的缓存」随流一起注入,保证客户端 hydration 不闪屏。
    面试时,如果只答“用 getDataFromTree 就行”会被直接判低分,因为 getDataFromTree 会阻断整个流,失去流式意义;正确姿势是用 React 18 的 pipeToNodeWritable + Suspense + Apollo useSuspenseQuery 做“分段注水”,并用 renderToPipeableStream 的 onShellReady/onAllReady 钩子精准控制流式节奏。

知识点

  • React 18 流式 API:renderToPipeableStream、onShellReady、onAllReady、bootstrapScripts
  • Apollo Client 3.8+ 的 @apollo/client/react/ssr 新方案:PreloadQuery + useSuspenseQuery,彻底废弃 getDataFromTree
  • 双端缓存序列化:服务端 cache.extract() → 全局变量 window.__APOLLO_STATE__ → 客户端 new ApolloClient({ cache: restore(window.__APOLLO_STATE__) })
  • 流式注水顺序:
    1. 外壳(Shell)渲染完成 → onShellReady 触发,先吐 <html><head>...</head><body><div id="root"> 及内联 script 状态;
    2. 剩余异步组件(带 Suspense)resolve → onAllReady 触发,继续吐剩余 HTML 并关闭流。
  • 错误边界与重试:在 onError 里区分“可恢复段”与“致命段”,结合 Sentry 上报,保证国内 4G/弱网场景下首屏可用。
  • 性能指标:TTFB、FCP、LCP、SSR 吞吐 QPS(Node 进程内存 < 600 MB,P99 < 80 ms)。

答案

下面给出可直接落地的「React 18 + Apollo Client 3.8」流式 SSR 最小可运行骨架,覆盖服务端、客户端、缓存注水三个环节,完全基于国内主流技术栈(Node 16、pnpm、Vite、ESM)。

  1. 服务端入口 server.jsx
import { renderToPipeableStream } from 'react-dom/server';
import { ApolloProvider, ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
import { PreloadQuery } from '@apollo/client/react/ssr';
import App from './App';
import { getDataFromTree } from '@apollo/client/react/ssr'; // 仅 fallback 用,不阻塞流

export default function render(url, res) {
  const cache = new InMemoryCache();
  const client = new ApolloClient({
    ssrMode: true,
    cache,
    link: createHttpLink({ uri: 'http://api.xxx.com/graphql', fetch }),
  });

  const jsx = (
    <ApolloProvider client={client}>
      <PreloadQuery>
        <App />
      </PreloadQuery>
    </ApolloProvider>
  );

  let didError = false;
  const { pipe, abort } = renderToPipeableStream(jsx, {
    bootstrapScripts: ['/static/client.js'],
    onShellReady() {
      // 关键:外壳已稳,先吐 head + 初始状态
      res.statusCode = didError ? 500 : 200;
      res.setHeader('Content-type', 'text/html; charset=utf-8');
      res.write(`<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>流式 SSR</title>
</head>
<body>
  <div id="root">`);
      pipe(res);
      // 紧接着注入缓存快照,保证 hydration 前可用
      res.write(`</div>
<script>
  window.__APOLLO_STATE__=${JSON.stringify(cache.extract()).replace(/</g, '\\u003c')};
</script>
</body>
</html>`);
    },
    onError(err) {
      didError = true;
      console.error(err);
    },
  });

  // 国内网络常有慢请求,设置超时兜底
  setTimeout(() => abort(), 8000);
}
  1. 客户端入口 client.jsx
import { hydrateRoot } from 'react-dom/client';
import { ApolloProvider, ApolloClient, InMemoryCache } from '@apollo/client';
import App from './App';

const client = new ApolloClient({
  cache: new InMemoryCache().restore(window.__APOLLO_STATE__),
  uri: '/graphql',
});

hydrateRoot(
  document.getElementById('root'),
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
);
  1. 组件侧使用 useSuspenseQuery 声明“关键查询”
import { useSuspenseQuery } from '@apollo/client';

const QUERY = gql`
  query HomePosts {
    posts {
      id
      title
    }
  }
`;

export default function Home() {
  const { data } = useSuspenseQuery(QUERY);
  return (
    <ul>
      {data.posts.map(p => (
        <li key={p.id}>{p.title}</li>
      ))}
    </ul>
  );
}

关键点回顾

  • PreloadQuery 把查询标记为“阻塞外壳”,React 会在数据就绪后才触发 onShellReady,保证首屏不白;
  • cache.extract() 必须在 onShellReady 回调里同步执行,否则流关闭后 cache 会被释放;
  • 所有非关键查询降级到普通 useQuery,由 Suspense 边界包裹,React 会自动流式补全。

拓展思考

  1. 微前端场景: qiankun 子应用也走流式 SSR 时,主应用需要把 __APOLLO_STATE__ 按子应用命名空间隔离,避免 cache 冲突;可基于 Apollo Client 3 的 possibleTypes + typePolicies 做“缓存分区”。
  2. 灰度与 AB:在 onShellReady 里根据 Cookie 决策是否启用流式,若用户处于老版本浏览器(如微信内核 < 8.0),可降级到 renderToString,保证兼容性。
  3. 大数据列表:对“分页 + 聚合”场景,可结合 GraphQL @defer + @stream 指令,把首屏前 10 条数据阻塞在 Shell,剩余 90 条异步流式下发,进一步降低 TTI。
  4. 边缘函数:国内云厂商(阿里云 EGA、腾讯云 SCF)已支持 Node 18 流式返回,把上述 renderToPipeableStream 逻辑下沉到边缘,可把 TTFB 控制在 50 ms 以内,但需注意边缘内存限制(128 MB),需要把 Apollo Cache 做 LRU 裁剪。