aboutsummaryrefslogtreecommitdiff
path: root/docs/guides/ecosystem/ssr-react.md
blob: 59d37db46d35e34ffa1e7dc594fd1601eb4c4dd4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
---
name: Server-side render (SSR) a React component
---

To render a React component to an HTML stream server-side (SSR):

```tsx
import { renderToReadableStream } from "react-dom/server";

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

const stream = await renderToReadableStream(
  <Component message="Hello from server!" />,
);
```

---

Combining this with `Bun.serve()`, we get a simple SSR HTTP server:

```tsx
Bun.serve({
  async fetch() {
    const stream = await renderToReadableStream(
      <Component message="Hello from server!" />,
    );
    return new Response(stream, {
      headers: { "Content-Type": "text/html" },
    });
  },
});
```

---

React `18.3` and later includes an [SSR optimization](https://github.com/facebook/react/pull/25597) that takes advantage of Bun's "direct" `ReadableStream` implementation.