RSC client hydration and routing
React Server Components (RSC) client support connects server-rendered RSC payloads to a live browser tree. It reuses payloads embedded in the first HTML response, fetches new payloads for later navigation, keeps payload promises stable for each provider, and restores router state before the first client render.
For the wider system view, see React Server Components integration. For the request and server-rendering path that produces these payloads, see RSC request and rendering flow. For the wider rendering platform, see Pro rendering platform.
Client payload path
The client payload path turns a server RSC response into a ReactNode. The browser first checks the page-scoped Embedded Payload Registry, which is the set of raw RSC payload chunks written into the HTML response; only a cache miss or an explicit refetch uses the RSC HTTP endpoint.
Embedded Payload Registry
The Embedded Payload Registry is the window.REACT_ON_RAILS_RSC_PAYLOADS global. Each entry is keyed by component name, serialized props, and, for a mounted root, the DOM node ID. The server creates the entry before the related component HTML can reach the browser, then appends raw Flight data chunks to it as the RSC stream progresses. window.REACT_ON_RAILS_RSC_ERRORS carries a matching error signal or development diagnostic.
The registry is page-scoped. It is therefore useful for initial hydration but must not become the source of truth after a soft page change. Navigation teardown removes the globals, while a new page starts with new entries.
References: packages/…/rscPayloadGlobals.ts• L16-30 packages/…/injectRSCPayload.ts• L72-85 packages/…/injectRSCPayload.ts• L1962-2016 packages/…/ClientSideRenderer.ts• L640-657
Payload parsing
An RSC payload is a stream of Flight-serialized data for one component and one props value. The browser parser reads the length-prefixed response format, keeps metadata separate from Flight bytes, and passes the bytes to React's RSC client runtime.
The same parsing path serves two sources. Embedded chunks are exposed as a readable stream that can receive later script pushes until the document is ready. Fetched responses are read without read-ahead so stream completion confirms that React received every queued record. Both paths return a normal promise so React can suspend on the result and route errors through the same boundary.
Network responses report HTTP failures before parsing begins. Request-preparation and transport failures become rejected promises with component and endpoint context, while serialized props stay out of the displayed source path. Abort errors remain identifiable so callers can treat cancellation differently from a failed request.
References: packages/…/getReactServerComponent.client.ts• L78-183 packages/…/getReactServerComponent.client.ts• L201-313 packages/…/getReactServerComponent.client.ts• L315-388 packages/…/getReactServerComponent.client.ts• L399-454 packages/…/utils.ts• L85-98
Initial hydration
wrapServerComponentRenderer creates the browser root for a registered server-component renderer. When the DOM root contains server HTML, React hydrates it; when it is empty, React creates a client root and renders the tree. The wrapper places the tree inside an RSCProvider and a top-level Suspense boundary so an RSC promise can resolve without changing the root contract.
The default provider factory wraps a root only when RSC support is configured for the Rails context. The provider uses the root ID and Rails context to select the embedded registry entry or the HTTP fetch path. It also checks the root's first child for a streamed Suspense marker and mirrors that boundary when needed for hydration parity.
References: packages/…/client.tsx• L48-65 packages/…/client.tsx• L103-145 packages/…/registerDefaultRSCProvider.client.tsx• L23-47 packages/…/defaultRSCProviderRegistry.ts• L19-51
The end-to-end browser sequence is shown below.
flowchart LR
A[Server RSC stream] --> B[Marked payload scripts]
B --> C[Embedded Payload Registry]
C --> D[Provider lookup]
D -->|entry exists| E[Parse embedded chunks]
D -->|entry absent| F[Fetch RSC endpoint]
F --> G[Parse length-prefixed response]
E --> H[React promise]
G --> H
H --> I[RSCRoute renders ReactNode]
Provider and cache lifecycle
An RSCProvider is the lifetime boundary for client RSC state. Each wrapped root gets its own Provider Cache of decoded payload promises, while the page has one shared Prefetch Store for work started before a React tree needs it.
Provider Cache
The Provider Cache maps a stable payload key to a decoded Promise<ReactNode>. A normal getComponent call returns the existing promise or starts one load. This makes repeated reads of the same component and props share work and gives React one value to suspend on.
The cache keeps at most 50 unpinned keys through least-recently-used eviction. In-flight payloads and mounted routes are pinned, so cache pressure cannot remove visible or active work. Pin counts support overlapping loads of the same key. A short retention window protects terminal browser failures from immediately opening a new request loop.
An evicted successful key keeps bounded marker state. If a mounted route later reloads that key, the marker stays active until the replacement settles. A successful replacement can then notify the route, while failed or incomplete replacement work leaves the prior recovery state available.
References: packages/…/RSCProvider.tsx• L157-220 packages/…/RSCProvider.tsx• L229-275 packages/…/RSCProvider.tsx• L356-495 packages/…/RSCProviderCache.ts• L16-54 packages/…/RSCProviderCache.ts• L57-89 packages/…/RSCProviderCache.ts• L127-159
Prefetch Store
The Prefetch Store is a page-scoped registry of decoded payload promises created outside React, such as by a router loader. A provider adopts a matching promise on its first cache miss, so one warm request can serve more than one provider cache. The store holds decoded promises rather than raw streams because a stream body can be consumed only once.
The Embedded Payload Registry takes priority over prefetch. A prefetch for an already embedded component is a no-op by default. A failed prefetch removes its own entry, so the next render behaves like a normal cache miss. The store is bounded and is cleared before a soft page render so old-page work cannot enter a new page.
References: packages/…/RSCPrefetchStore.ts• L21-45 packages/…/RSCPrefetchStore.ts• L48-82 packages/…/prefetchServerComponent.client.ts• L25-54 packages/…/prefetchServerComponent.client.ts• L56-100
Route rendering and refresh
RSCRoute is the bridge from a client component to a named server component. It reads the provider promise and renders the resulting ReactNode, while its error boundary adds the component name and props to failures.
An imperative refetch always bypasses the Prefetch Store and requests fresh data. The provider swaps the promise inside a transition, so the prior route content can remain visible while the new payload resolves. In production, a failed refetch can keep the last successful content visible and expose a refetchError; development keeps failures loud.
References: packages/…/RSCRoute.tsx• L42-72 packages/…/RSCRoute.tsx• L184-285 packages/…/RSCRoute.tsx• L317-362 packages/…/RSCProvider.tsx• L505-665
Request tracking and stream coordination
RSC request tracking keeps the server-side streams for one HTML response isolated from other requests. It lets the renderer serve the same source payload to React SSR and to HTML injection, then closes all work when the response ends or the client disconnects.
Stream ownership
RSCRequestTracker records each generated RSC stream and notifies injection code as soon as a component asks for a payload. The source stream is split into one branch for React and one branch for payload injection. This prevents a slow injection consumer from stopping the server render branch.
When the HTML response closes, the tracker ends its tracked work and destroys the original sources. Expected disconnect cleanup is marked so it is not reported as a real truncated RSC payload. Genuine stream truncation remains visible to diagnostics.
References: packages/…/RSCRequestTracker.ts• L65-115 packages/…/RSCRequestTracker.ts• L118-167 packages/…/RSCRequestTracker.ts• L262-374 packages/…/injectRSCPayload.ts• L2170-2196
HTML injection order
The injection layer combines three timing needs: the browser must know the payload array before it hydrates, streamed markup must remain valid HTML, and payload chunks may arrive after the markup that references them. It therefore emits initialization scripts first, relevant stylesheet resources next, then HTML, and finally payload push scripts.
React's stream flush signal is the main boundary for sending a complete render batch. A short timer remains as a fallback when that signal is absent. The injector holds incomplete HTML boundaries, including open raw-text elements, so framework scripts do not land inside application markup. It can also hold a Suspense reveal briefly while inferred RSC client styles become ready.
References: packages/…/injectRSCPayload.ts• L1653-1672 packages/…/injectRSCPayload.ts• L1691-1713 packages/…/injectRSCPayload.ts• L1742-1894 packages/…/injectRSCPayload.ts• L1913-1973 packages/…/injectRSCPayload.ts• L2173-2208
Stylesheet readiness
Manifest CSS is the per-client-chunk stylesheet map recorded in loadable-stats.json. When streamed RSC data names a client chunk, the injector can emit its stylesheet with the shared rsc-css precedence before the related reveal. This gates the streamed boundary rather than the first HTML shell paint.
The stream also promotes matching stylesheet preload tags to render-blocking stylesheet links. If loadable-stats.json is missing or is not ready, the injector keeps the streamed preload fallback and retries with backoff. A malformed or unreadable file remains visible through a warning. Missing-file events use a protected host callback so the Node renderer can report the issue without letting bundle code replace that diagnostic path.
References: packages/…/injectRSCPayload.ts• L126-205 packages/…/injectRSCPayload.ts• L297-357 packages/…/injectRSCPayload.ts• L1469-1617 packages/…/injectRSCPayload.ts• L2019-2061 packages/…/vm.ts• L63-80 packages/…/vm.ts• L683-694
Hydration DOM markers
Hydration DOM markers give the browser a safe way to identify framework-owned payload scripts and resources in a stream that also contains application HTML. They also let the client repair resource placement before React starts hydration.
Payload script markers
Every injected payload initializer and payload push script carries data-react-on-rails-rsc-payload="true". The marker is not the payload key; it only identifies scripts that belong to the RSC injection path. The key remains inside the script and maps the data to one component, props value, and root.
The marker is shared by the server producer and the client preparer. Keeping it in one definition prevents the browser from treating a framework script as application content or leaving it in the root where React expects component nodes.
References: packages/…/rscDomMarkers.ts• L16-19 packages/…/injectRSCPayload.ts• L64-85 packages/…/rscHydrationDom.ts• L16-32
Resource preparation
Before hydration, the client removes the leading payload initializer from the root and moves streamed RSC stylesheet links and async scripts into document.head. It stops when it reaches ordinary root content, so it does not scan or change the application tree.
Preparation runs only when Rails context includes an RSC payload generation path. It deduplicates resources already in the head and recognizes the shared rsc-css precedence bucket. This supports React's resource placement rules without adding a wrapper or changing the server-rendered component shape.
References: packages/…/rscHydrationDom.ts• L23-47 packages/…/rscHydrationDom.ts• L71-106 packages/…/rscHydrationDom.ts• L108-135 packages/…/client.tsx• L120-129
Diagnostics and observability
RSC diagnostics preserve the reason a server component failed when React exposes only a generic stream error. The system separates a safe production signal from richer development and test detail, then attaches component and source context where it can.
Stream diagnostics
The length-prefixed metadata can carry hasErrors and a renderingError with a message or stack. The parser builds a named RSC diagnostic, extracts the first useful application module path, and keeps the original stream bytes intact. If React later reports its generic Server Components render error, the diagnostic is merged with that error.
On the server, diagnostics captured while the RSC stream is transformed are retained for the later render phase. This covers errors that appear after the decoded root has been accepted and lets request-scoped tracking report the useful component context. When several RSC components fail during deferred rendering, the system reports them as candidates instead of claiming that it knows which component caused the generic error. Duplicate diagnostics for the same component and message are removed within one request.
References: packages/…/rscDiagnostics.ts• L67-108 packages/…/rscDiagnostics.ts• L110-153 packages/…/rscDiagnostics.ts• L156-225 packages/…/rscDiagnostics.ts• L228-263 packages/…/getReactServerComponent.client.ts• L123-181 packages/…/getReactServerComponent.server.ts• L30-74 packages/…/RSCRequestTracker.ts• L169-239
Client error signals
Server injection writes a generic error signal to the page registry when an RSC stream reports failure. Development and test pages may receive the server message and stack; other environments receive only the positive error signal. The browser uses that metadata when an embedded payload fails, while fetched payloads collect metadata during response parsing.
Network failures are wrapped with the component and endpoint path but redact serialized props. Abort errors remain identifiable so callers can treat cancellation differently from a failed request. Console replay is separate from Flight data and is enabled for normal navigation fetches, not for adopted prefetches.
Missing loadable-stats.json is a non-fatal diagnostic. The injector reports it through a non-enumerable host callback, and the Node renderer logs the first such event for the process while continuing with streamed preload fallback. This keeps a deployment asset problem visible without turning it into a failed render.
References: packages/…/injectRSCPayload.ts• L99-123 packages/…/injectRSCPayload.ts• L179-205 packages/…/getReactServerComponent.client.ts• L99-165 packages/…/getReactServerComponent.client.ts• L201-313 packages/…/getReactServerComponent.client.ts• L347-364 packages/…/prefetchServerComponent.client.ts• L82-100 packages/…/vm.ts• L63-80
Renderer tracing
Optional OpenTelemetry tracing gives the Node renderer a request view of SSR work. It can connect the SSR request span to child work such as bundle handling, VM execution, result preparation, and incremental rendering without placing the rendering request payload in span attributes.
The renderer can create and own its provider or attach its tracing adapters to an application-owned global provider. The existing-provider path requires a working context manager and leaves provider setup and shutdown with the host. Managed providers disable instrumentations before shutdown and bound shutdown time so worker shutdown can complete.
References: packages/…/opentelemetry.ts• L51-85 packages/…/opentelemetry.ts• L184-249 packages/…/opentelemetry.ts• L295-341 packages/…/opentelemetry.ts• L380-565 packages/…/opentelemetryConfig.ts• L85-175 packages/…/opentelemetry.test.ts• L661-723
TanStack Router integration
The TanStack Router integration keeps the server-rendered route tree and the first browser route tree equivalent. It transfers the server URL and resolved route data to the client, restores that state before RouterProvider renders, and starts normal router loading only after hydration.
Server router state
The server creates a TanStack Router with memory history at the normalized Rails request URL. It waits for router.load() before rendering RouterProvider, then sends the client the URL and the state needed to reproduce the loaded route tree. This state can include application data returned by the router's dehydration hook and a compact record for each server match.
The server sanitizes route errors for production before it renders or dehydrates the tree. It also carries loader data, route context, status, update time, and safe error details when those values exist. This keeps the HTML and the client hydration payload based on the same route state.
The server and client both render RouterProvider directly. An extra Suspense or Await wrapper would change the initial tree and can cause React to abandon hydration.
References: packages/…/serverRender.ts• L28-57 packages/…/serverRender.ts• L80-126 packages/…/serverRender.ts• L129-243 packages/…/types.ts• L100-127 packages/…/index.ts• L82-126
Client router hydration
The client creates a router with browser history during render. When dehydrated state exists, it matches the current location and applies the server match data before the first RouterProvider render. This restores loader results, route context, status, and server errors before React compares the client tree with server HTML.
The client sets a temporary router SSR flag so TanStack Router does not start a second load during hydration. It supports both the older internal store and the newer stores API in TanStack Router 1.x, and it checks the required interface before use. If server match data is missing, a pending match becomes successful to avoid an initial suspension; development logs the route ID. TanStack Router is an optional peer in the supported range >=1.139.0 <2.0.0.
The client also runs the router's custom hydration hook and warms the matched route chunks before normal loading. It shares initialization state by router instance so React Strict Mode does not repeat these render-phase actions when a caller reuses a router.
References: packages/…/clientHydrate.ts• L31-62 packages/…/clientHydrate.ts• L106-195 packages/…/clientHydrate.ts• L221-280 packages/…/clientHydrate.ts• L323-465 packages/…/types.ts• L35-87 packages/…/package.json• L86-102
Post-hydration navigation
The temporary SSR flag prevents TanStack Router's automatic first load from changing state during hydration. After mount, the integration waits for the custom hydration hook and matched route chunks, then calls router.load() to enable normal client navigation.
The effect clears only the temporary flag when loading settles and leaves a user-provided SSR value unchanged. It cancels router work on unmount and reports load errors while the component remains mounted. Matched route chunks are preloaded before the post-hydration load when the router exposes that capability, which reduces a second suspension during the transition to normal navigation.
References: packages/…/clientHydrate.ts• L282-320 packages/…/clientHydrate.ts• L467-571 packages/…/clientHydrate.ts• L573-608 packages/…/index.ts• L129-149
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the payload marker constant aligned between injectRSCPayload.ts, rscDomMarkers.ts, and rscHydrationDom.ts.
- Keep the normal payload key and the root-scoped embedded key compatible across utils.ts, RSCProvider.tsx, getReactServerComponent.client.ts, and injectRSCPayload.ts.
- Preserve Embedded Payload Registry precedence over the Prefetch Store unless a caller explicitly requests sibling-root warming.
- Keep decoded-promise adoption and self-eviction rules aligned between prefetchServerComponent.client.ts, RSCPrefetchStore.ts, and RSCProvider.tsx.
- Keep the default provider factory's configuration gate aligned with the root wrapper and Rails context so unsupported roots are not wrapped accidentally.
- Keep the provider cache's pin, eviction, failure-retention, and last-successful-payload bookkeeping aligned when changing RSCProvider.tsx or RSCProviderCache.ts.
- Keep the client stream parser's completion and diagnostic state aligned with RSCStreamCompletion.ts, rscDiagnostics.ts, and the server stream transform.
- Treat the dehydrated router shape as a server-to-client contract. Changes in serverRender.ts must be reflected in clientHydrate.ts and types.ts.
- Re-check TanStack Router private hydration interfaces when changing the supported router range.
- Keep length-prefixed metadata handling aligned between the server stream producer, injectRSCPayload.ts, transformRSCNodeStream.ts, and getReactServerComponent.client.ts.
- Preserve page-unload cleanup for both embedded globals and the module-level Prefetch Store during soft navigation.
- Keep loadable-stats.json placement, the missing-stats host callback, and the streamed stylesheet fallback aligned between injectRSCPayload.ts and worker/vm.ts.
- Keep OpenTelemetry provider ownership, span context wiring, and shutdown behavior aligned with the worker lifecycle when changing renderer diagnostics.
- Keep package peer ranges and packed compatibility checks aligned with the export conditions that select SSR, streaming, and RSC behavior.
- Keep the TanStack Router server match shape aligned between error sanitization, dehydration, client restoration, and types.ts.
- Keep the render-time match injection and temporary SSR flag aligned with the TanStack Router version range and its legacy or modern store API.
- Keep custom router hydration and matched route-chunk preload completion ahead of the first post-hydration
router.load().
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| RSC payload generation path is missing from Rails context | A provider cannot fetch a missing or refetched payload | Validate RSC support configuration before mounting an RSC root |
| Payload initializer runs after related HTML | Hydration cannot find the expected embedded payload and may issue an unnecessary request | Inject initialization scripts before component HTML |
| Provider and embedded keys use different component props or root IDs | The browser misses an available payload or adopts data for the wrong root | Treat key construction as one shared contract |
| A failed prefetch remains in the Prefetch Store | A later route render reuses a known-bad promise | Self-evict failed prefetch entries |
| A payload stream ends with an incomplete length-prefixed record | React receives no complete payload and the route reports a parsing failure | Flush the parser at end of stream and report incomplete input |
| A terminal browser rejection is evicted before its retention window ends | Render-driven retries can reopen a request loop | Keep terminal failures pinned for the bounded retention window |
| loadable-stats.json is missing or malformed | Inferred client CSS is unavailable and a streamed boundary may reveal with only preload fallback | Ship the stats file with the renderer bundle and keep the streamed preload fallback active |
Router hydration state is applied after RouterProvider renders | The first client tree differs from server HTML | Apply matches and the temporary SSR flag during render |
| TanStack Router removes the required private hydration interface | Client hydration cannot restore server matches | Validate the interface and keep the router version in the supported range |
| Server match data is not JSON-safe or does not match the client match shape | Loader-driven output or route errors differ during hydration | Keep server sanitization, dehydration, client restoration, and the shared types in sync |
| Post-hydration loading starts before custom hydration or route chunks finish | Client navigation can race with restored state or suspend again | Await both optional steps before calling router.load() |
| A real stream truncation is mistaken for expected disconnect cleanup | Operators lose evidence of an incomplete RSC payload | Mark only tracker-owned teardown as expected and report other truncation |
| Renderer tracing attaches to a global provider without a working context manager | SSR spans are not installed even though initialization appears configured | Register the host provider with its context manager before renderer initialization |
Key files
| File | Why to read it |
|---|---|
| packages/…/getReactServerComponent.client.ts | Defines embedded-payload lookup, network fetch, stream parsing, and client error wrapping |
| packages/…/getReactServerComponent.server.ts | Connects server RSC streams to React SSR and preserves stream diagnostics for later render errors |
| packages/…/injectRSCPayload.ts | Shows how server RSC streams become browser registry scripts, stylesheet hints, diagnostics, and ordered HTML output |
| packages/…/client.tsx | Defines root hydration, provider creation, Suspense shape, and teardown |
| packages/…/defaultRSCProviderRegistry.ts | Defines when the default provider can wrap a root and reports whether it did so |
| packages/…/RSCProvider.tsx | Defines provider lifetime, payload reuse, refetch behavior, recovery, and route-visible state |
| packages/…/RSCProviderCache.ts | Defines cache bounds, reference-counted pins, and eviction behavior |
| packages/…/RSCPrefetchStore.ts | Defines page-scoped prefetch adoption and cleanup |
| packages/…/prefetchServerComponent.client.ts | Defines the public warm-cache prefetch contract |
| packages/…/RSCRoute.tsx | Shows how client trees render and refresh server components |
| packages/…/RSCRequestTracker.ts | Defines request-local stream ownership and teardown |
| packages/…/rscHydrationDom.ts | Defines marker recognition and pre-hydration resource movement |
| packages/…/rscDiagnostics.ts | Defines RSC error context, correlation, and safe diagnostic merging |
| packages/…/vm.ts | Defines the renderer host diagnostic boundary and isolated VM lifecycle used by RSC streaming |
| packages/…/opentelemetry.ts | Defines renderer tracing attachment, span wiring, ownership, and shutdown |
| packages/…/serverRender.ts | Defines server URL loading, route error sanitization, and dehydrated router state creation |
| packages/…/clientHydrate.ts | Defines match restoration, router hydration parity, route chunk preload, and post-hydration loading |
| packages/…/types.ts | Defines the server-to-client router state contract and supported hydration interfaces |
| packages/…/utils.ts | Defines URL search normalization and cross-runtime hydration error creation |
| packages/…/index.ts | Defines the public TanStack Router render-function integration |
| packages/…/package.json | Defines the package exports and peer-version boundaries for RSC and TanStack Router |