Server-Side Rendering and Hydration
Relevant source files
The following files were used as context for generating this wiki page:
- packages/react-dom/src/tests/ReactDOMFizzServer-test.js
- packages/react-dom/src/tests/ReactDOMFloat-test.js
- packages/react-dom/src/tests/ReactDOMFizzServerBrowser-test.js
- packages/react-dom/src/tests/ReactDOMFizzServerNode-test.js
- packages/react-dom/src/tests/ReactDOMFizzSuppressHydrationWarning-test.js
- packages/react-dom/src/tests/ReactRenderDocument-test.js
- packages/react-dom/src/tests/ReactDOMFizzShellHydration-test.js
- packages/react-dom/src/tests/ReactDOMFizzSuspenseList-test.js
- packages/react-dom/src/server/ReactDOMLegacyServerImpl.js
- packages/react-server-dom-webpack/src/tests/ReactFlightDOM-test.js
React's Server-Side Rendering (SSR) capability, implemented through the "Fizz" server architecture, allows developers to render React components on the server into a stream of HTML. This initial HTML can be sent to the browser, enabling users to see the page content before all the JavaScript has loaded. Once the JavaScript loads, React "hydrates" the static HTML, attaching event listeners and making the page interactive. This process improves perceived performance and SEO.
The core of this system is designed for streaming, meaning the server can send a complete HTML shell first, followed by additional content for suspended components as they become ready. This is particularly effective for applications with data-fetching requirements, as it avoids an all-or-nothing approach to rendering. The client-side hydration process is designed to be resilient, capable of handling streamed content, recovering from server errors, and managing mismatches between server-rendered and client-rendered output.
High-Level Architecture
The SSR and hydration process involves a coordinated effort between the server and the client. The server generates the initial HTML, and the client takes over to make it interactive.
This diagram illustrates the end-to-end flow from a user request to an interactive page.
Server-Side Rendering with Fizz
The Fizz server architecture provides APIs to render React components into a stream. The primary API for Node.js environments is renderToPipeableStream, while Edge and Browser environments use renderToReadableStream.
Sources: packages/react-dom/src/tests/ReactDOMFizzServerNode-test.js, packages/react-dom/src/tests/ReactDOMFizzServerBrowser-test.js
renderToPipeableStream (Node.js)
This function returns an object with a pipe method to send the HTML to a Node.js writable stream and an abort method to cancel the render.
Key Options:
| Option | Description | Source |
|---|---|---|
bootstrapScriptContent | Inline script content to be included in the stream. | ReactDOMFizzServer-test.js:630-649 |
bootstrapScripts | An array of script URLs to be included as <script async> tags. | ReactDOMFizzServer-test.js:630-649 |
bootstrapModules | An array of module script URLs to be included as <script type="module" async> tags. | ReactDOMFizzServer-test.js:630-649 |
onShellReady | A callback that fires when the initial shell is ready to be streamed. | ReactDOMFizzServerNode-test.js:52-62 |
onAllReady | A callback that fires when all rendering, including async content, is complete. | ReactDOMFizzServerNode-test.js:108-124 |
onError | A callback for handling recoverable errors that occur during rendering. | ReactDOMFizzServer-test.js:1010-1014 |
onShellError | A callback for handling fatal errors that prevent the initial shell from rendering. | ReactDOMFizzServerNode-test.js:151-164 |
unstable_externalRuntimeSrc | Specifies an external script to load the Fizz runtime, instead of inlining it. | ReactDOMFizzServer-test.js:11049-11066 |
Streaming and <Suspense>
A key feature of Fizz is its ability to handle asynchronicity using <Suspense>. When a component suspends on the server (e.g., while fetching data), React sends the HTML for its fallback prop first. Once the suspended component's data is resolved, React streams the component's actual HTML to the client, along with a small inline script to replace the fallback.
This sequence diagram shows how a component with a data dependency is rendered and streamed.
Client-Side Hydration
Hydration is the process of attaching event listeners to the server-rendered HTML to make the application interactive. This is initiated on the client using ReactDOMClient.hydrateRoot.
Sources: packages/react-dom/src/tests/ReactRenderDocument-test.js:55-66
Hydration Process
- Initial Render: The browser renders the initial HTML received from the server.
- JavaScript Execution: The client-side JavaScript bundle is downloaded and executed.
hydrateRootCall:ReactDOMClient.hydrateRootis called with the root DOM element and the React component tree.- Reconciliation: React walks the client-side component tree and the existing server-rendered DOM tree, attempting to match them up and attach event listeners.
- Interactivity: Once hydration is complete, the application is fully interactive.
Handling Mismatches
If the client-rendered output does not exactly match the server-rendered HTML, React will log a hydration mismatch error in development. Instead of attempting to patch the differences, React will perform a full client-side render to ensure a consistent state.
The suppressHydrationWarning prop can be used to prevent this warning for specific elements where a mismatch is expected and intentional (e.g., a timestamp). This prop only suppresses warnings for text content and attribute mismatches; structural differences will still trigger an error.
// Example of suppressing a warning for a timestamp
<span suppressHydrationWarning={true}>
{isClient ? new Date().toISOString() : 'Server Timestamp'}
</span>
Sources: packages/react-dom/src/tests/ReactDOMFizzSuppressHydrationWarning-test.js:101-125
Error Recovery and Client Render Fallback
If the server fails to render a Suspense boundary (due to an error or an abort), it sends the fallback HTML with a special marker. When the client attempts to hydrate, it detects this marker and understands that the server-rendered content is incomplete.
The client will then attempt to render the boundary itself. This ensures that even if part of the server render fails, the application can still recover and become interactive on the client.
This diagram shows the error recovery flow.
Resource Management
React's SSR includes advanced resource management for <link>, <style>, and <script> tags to optimize loading performance.
Hoisting
When React encounters resource or hoistable tags (<link>, <title>, <meta>) anywhere in the render tree, it automatically "hoists" them to the <head> of the document. This ensures that critical resources are discovered by the browser as early as possible.
- Stylesheet Resources:
<link rel="stylesheet" ...>and<style>tags with aprecedenceprop are treated as resources. React manages their insertion order in the<head>based on their precedence value, ensuring deterministic styling. - Script Resources:
<script async src="...">tags are also hoisted to the head. - General Hoistables: Tags like
<title>and<meta>are hoisted without any special ordering beyond their discovery order.
Sources: packages/react-dom/src/tests/ReactDOMFloat-test.js:1432-1460, packages/react-dom/src/tests/ReactDOMSingletonComponents-test.js:231-255
Preloading and Pre-initialization APIs
React provides imperative APIs via react-dom to give the browser hints about resources that will be needed soon. These are crucial for optimizing the critical rendering path.
| API | Description |
|---|---|
ReactDOM.preload(href, options) | Hints to the browser that a resource should be fetched with low priority. Useful for resources needed for future navigations. |
ReactDOM.preinit(href, options) | Fetches and executes a resource with high priority. For stylesheets, it inserts a <link rel="stylesheet">. For scripts, it inserts a <script async>. |
ReactDOM.preconnect(href, options) | Establishes a connection to a server, including DNS lookup, TCP handshake, and TLS negotiation. |
ReactDOM.prefetchDNS(href) | Hints to the browser to perform a DNS lookup for a domain. |
These APIs can be called during render on both the server and the client. On the server, they result in <link> tags being emitted in the initial HTML. On the client, they dynamically create and insert the corresponding tags into the document head.
Sources: packages/react-dom/src/tests/ReactDOMFloat-test.js:3155-3189, packages/react-dom/src/tests/ReactDOMFloat-test.js:3710-3741
Conclusion
React's server-side rendering and hydration architecture is a sophisticated system designed for performance and resilience. By streaming HTML, handling asynchronicity with Suspense, and providing fine-grained control over resource loading, it enables the creation of fast, interactive, and SEO-friendly web applications. The ability to recover from server-side errors on the client ensures a robust user experience, even when parts of the rendering process fail.