> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 服务器端渲染（SSR）React 组件

首先，安装 `react` 和 `react-dom`：

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
# 可以使用任意包管理器
bun add react react-dom
```

***

要将 React 组件在服务器端渲染为 HTML 流（SSR）：

```tsx ssr-react.tsx icon="file-code" theme={"theme":{"light":"github-light","dark":"dracula"}}
import { renderToReadableStream } from "react-dom/server";

function Component(props: { message: string }) {
  return (
    <body>
      <h1>{props.message}</h1>
    </body>
  );
}

const stream = await renderToReadableStream(<Component message="来自服务器的问候！" />);
```

***

将其与 `Bun.serve()` 结合，我们得到一个 SSR HTTP 服务器：

```tsx server.tsx icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
Bun.serve({
  async fetch() {
    const stream = await renderToReadableStream(<Component message="来自服务器的问候！" />);
    return new Response(stream, {
      headers: { "Content-Type": "text/html" },
    });
  },
});
```

***

React `19` 及以后版本包含一个利用 Bun “直接” `ReadableStream` 实现的 [SSR 优化](https://github.com/facebook/react/pull/25597)。如果遇到类似 `export named 'renderToReadableStream' not found` 的错误，请确保安装了 `react` 和 `react-dom` 的 `19` 版本，或者从 `react-dom/server.browser` 而非 `react-dom/server` 导入。更多信息请参见 [facebook/react#28941](https://github.com/facebook/react/issues/28941)。
