Server-rendering protocol and Ruby bridge
The server-rendering bridge turns a Rails component request into JavaScript for a server runtime and turns the runtime result back into HTML, metadata, or a stream of render chunks. Ruby owns request setup, renderer selection, response parsing, and error reporting, while the JavaScript runtime owns component execution and result encoding. See Rails integration for the wider Rails flow, Rails engine and configuration for setup, JavaScript runtime and registration for the registration contract, component rendering and hydration for browser use of the result, and development and diagnostics for troubleshooting.
Rendering boundary
The rendering boundary connects Rails helpers to the registered components in the server JavaScript bundle. It keeps the Rails request model on one side and the JavaScript render contract on the other.
Request and response roles
Rails supplies the component name, props, Rails context, store setup, and render options. The JavaScript runtime returns a render result that carries content plus the state needed for client replay and error handling.
| Side | Main responsibility | Result of the boundary |
|---|---|---|
| Ruby and Rails | Build a safe render request and choose a renderer pool. | JavaScript expression for one render. |
| JavaScript runtime | Find the registered component and render it. | HTML or another supported render value with metadata. |
| Ruby and Rails | Decode the response and apply error policy. | HTML for the view or a server-rendering error. |
The public Ruby entry point is ReactOnRails::ServerRenderingPool. It delegates to the open-source embedded JavaScript pool or to the Pro rendering path. The JavaScript entry point is ReactOnRails.serverRenderReactComponent, with stream-capable variants selected for progressive rendering. RenderOptions also validates hydration scheduling and prevents unsupported scheduled hydration in the Pro path. References: react_on_rails/…/server_rendering_pool.rb• L8-23, react_on_rails/…/render_options.rb• L7-24, react_on_rails/…/render_options.rb• L170-191, packages/…/index.ts• L667-685
Store hydration scope
The store registry gives rendered components access to stores that Rails hydrated for the page. When a request scope is available, it uses a store map bound to that scope; otherwise it uses the shared hydrated-store map. This keeps store lookup tied to the active render scope when the runtime supplies one.
Store access is name-based. A missing store can return undefined when the caller allows it, or raise an error that explains whether no stores were hydrated or the requested name is not present. Store generators are registered separately from hydrated store instances, so registration and hydration remain distinct parts of the render contract.
References: packages/…/StoreRegistry.ts• L3-20 packages/…/StoreRegistry.ts• L52-84 packages/…/StoreRegistry.ts• L104-110
Request construction
Rails builds one JavaScript expression for each server render. The expression carries request data into the JavaScript API instead of asking the JavaScript bundle to know about Rails view helpers.
Render request data
The helper serializes props and Rails context, adds any required Redux store setup, and passes the component name and render options to the JavaScript code generator. It also checks the renderer pool before a render so development requests use the current server bundle. RenderOptions resolves request values from per-render options first and then from application configuration. A valid REACT_ON_RAILS_PRERENDER_OVERRIDE value can override the configured prerender choice for the process.
The request data has these roles:
- Component name: Identifies a component or registered render function.
- Props: Carries server data into the component. Ruby converts a hash to JSON before placing it in the expression.
- Rails context: Carries request data that components need to match server and client behavior.
- Store setup: Creates only the stores named by the render options.
- Render options: Controls the DOM id, hydration policy, trace data, error behavior, and sync or stream mode.
The helper escapes JSON line-separator characters before it places props in JavaScript. This keeps valid JSON strings valid JavaScript expressions. References: react_on_rails/…/helper.rb• L894-895, react_on_rails/…/helper.rb• L965-1005, react_on_rails/…/helper.rb• L1028-1051, react_on_rails/…/render_options.rb• L31-66, react_on_rails/…/render_options.rb• L73-100
JavaScript request expression
ReactOnRails::ServerRenderingJsCode wraps the request in a function that defines the Rails context, initializes stores, defines props, and calls the JavaScript server-render API. The open-source path calls serverRenderReactComponent; the Pro path can select normal streaming, HTML streaming, or React Server Components payload rendering.
This generated expression is the request contract. The server bundle must expose the selected API and the component must be registered under the requested name. In Pro streaming mode, the expression can also carry manifest data and hooks for async props or RSC payload generation. See JavaScript runtime and component registration for the registration side of this contract.
References: react_on_rails/…/server_rendering_js_code.rb• L14-49 react_on_rails_pro/…/server_rendering_js_code.rb• L106-166
Render modes
Render options select whether Ruby receives one completed result or a sequence of chunks. Sync rendering is the simple path; HTML streaming sends progressive HTML; RSC payload streaming sends React Server Components data for the Pro flow.
| Mode | Ruby-facing behavior | Main use |
|---|---|---|
sync | Wait for one encoded result. | Complete server-rendered HTML. |
html_streaming | Consume content chunks as they arrive. | Progressive HTML delivery. |
rsc_payload_streaming | Consume a stream of RSC payload chunks and control messages. | Pro React Server Components rendering. |
Ruby treats a stream as a chunk source. It checks each content chunk for a render error and lets the stream policy decide whether an error should raise before or after the shell is ready. The related RSC lifecycle is described in RSC request and rendering flow.
References: react_on_rails/…/render_options.rb• L170-191 react_on_rails/…/helper.rb• L956-1025 react_on_rails_pro/…/node_rendering_pool.rb• L68-105
Rendering pools
The rendering pool hides where JavaScript runs and gives Rails one call for server rendering. The selected pool also owns renderer reuse and bundle refresh behavior.
Embedded JavaScript pool
The open-source pool keeps a connection pool of embedded JavaScript contexts. Each context loads the configured server bundle and the small runtime helpers needed for server evaluation. In development, a changed bundle causes the pool to reset so new requests do not use stale code.
The pool can read a local bundle or fetch a bundle from an HTTP URL. Remote source is decoded from its declared character set and converted to valid UTF-8 before the JavaScript runtime reads it. A load failure becomes a server-bundle error before component rendering starts. URL credentials, including credentials in malformed URLs and passwords containing @, are removed from load errors. The pool also captures server console output so Ruby can log it or send it back for browser replay.
References: react_on_rails/…/ruby_embedded_java_script.rb• L48-75 react_on_rails/…/ruby_embedded_java_script.rb• L144-200 react_on_rails/…/ruby_embedded_java_script.rb• L241-257 react_on_rails/…/ruby_embedded_java_script.rb• L426-487
Pro renderer pool
The Pro pool presents the same Ruby call while allowing JavaScript to run in a separate Node renderer. Ruby sends the generated expression to that renderer over HTTP and can reuse renderer connections. The path also supports stream responses, renderer bundle identity, and an optional fallback to embedded JavaScript.
This separation lets Rails keep the same request and response contract while the execution service changes. Renderer cache and deployment behavior belong with the Pro rendering platform rather than with the base Ruby bridge.
References: react_on_rails_pro/…/pro_rendering.rb• L16-45 react_on_rails_pro/…/node_rendering_pool.rb• L22-66 react_on_rails_pro/…/renderer_http_client.rb• L617-657
Node VM context pool
The Pro Node worker keeps compiled bundle contexts for reuse. It limits retained contexts and removes older or less-used contexts when the limit is reached. This keeps render latency low without allowing bundle revisions to grow memory without bound. References: packages/…/vm.ts• L95-148, packages/…/vm.ts• L504-573
The pool treats a set of bundles as a generation. A newly observed generation can run while an older generation drains, then the older contexts retire after the drain period. The worker can also prewarm the declared current generation so readiness reflects a complete usable bundle set. References: packages/…/vm.ts• L243-380, packages/…/vm.ts• L1105-1155
Each request receives an execution context with request-local shared state. The worker removes that state from the reusable VM as soon as code execution ends, while retaining it for later update chunks in the same request. This prevents concurrent requests from sharing request data. References: packages/…/vm.ts• L886-910, packages/…/vm.ts• L963-1019
Response protocol
The response protocol lets Ruby carry both text content and structured render state without confusing content bytes with metadata. The same envelope supports one result and progressive streams.
Render result metadata
The JavaScript side places render state in metadata and sends the content as a separate payload. The metadata can report client props, server console replay code, render errors, an error flag, and whether a streaming shell is ready.
The TypeScript response shape is:
| Field | Meaning |
|---|---|
html | Rendered string, structured render value, or null. |
clientProps | Props that the browser must use during hydration when the render supplies them. |
consoleReplayScript | Browser script that replays server console messages. |
hasErrors | Whether the JavaScript render saw an error. |
renderingError | Optional message and stack from the JavaScript side. |
isShellReady | Whether a streamed response has produced its shell. |
For a normal string result, Ruby uses the content as HTML. For a structured result, the envelope marks the payload as an object so Ruby can decode it before the view consumes it. References: packages/…/index.ts• L413-428, packages/…/serverRenderUtils.ts• L11-37
Length-prefixed chunks
The current wire format is one record per chunk:
<metadata JSON>\t<content byte length in hex>\n<raw UTF-8 content bytes>
The length counts bytes rather than Ruby or JavaScript characters. This matters for non-ASCII HTML. Ruby can feed the parser with partial network reads; the parser waits until it has a full header and then a full payload before it yields a chunk.
The payloadType metadata value tells Ruby how to decode the payload:
stringmeans the raw bytes are HTML or other text.objectmeans the bytes contain JSON for a structured value ornull.messageTypevaluespropRequestandrenderCompleteare control records in the Pro stream. They do not become HTML chunks.
The parser rejects missing separators, invalid length values, invalid metadata, invalid object payloads, and truncated streams. It uses the lenient JSON reader for lone surrogate escapes that JavaScript can emit.
References: react_on_rails/…/length_prefixed_parser.rb• L7-15 react_on_rails/…/length_prefixed_parser.rb• L25-41 react_on_rails/…/length_prefixed_parser.rb• L56-87 react_on_rails/…/length_prefixed_parser.rb• L96-171 packages/…/serverRenderUtils.ts• L39-99
Legacy JSON responses
Ruby still accepts a completed JSON result for older embedded bundles. It chooses the length-prefixed parser when the result has the protocol separator. Otherwise it uses the lenient JSON parser and then replays server console messages when server logging is enabled.
This compatibility rule applies to non-streaming results. Stream responses use the incremental length-prefixed parser because Ruby must separate records as bytes arrive.
References: react_on_rails/…/ruby_embedded_java_script.rb• L90-124 react_on_rails/…/ruby_embedded_java_script.rb• L486-513
Error handling
The bridge keeps renderer transport errors, bundle load errors, JavaScript render errors, and protocol errors distinct. That distinction gives an engineer a useful next step instead of one generic server-rendering failure.
Error classes
The main error paths are:
| Error kind | Meaning | Ruby response |
|---|---|---|
| Bundle load or compile error | The server bundle could not be loaded or compiled. | Raise a bundle error with bundle and setup guidance. |
| Renderer connection error | Rails could not reach the separate Node renderer. | Raise a connection-focused error with the target and transport checks. |
| JavaScript render error | The bundle ran but component code failed. | Return an error result or raise according to render options. |
| Protocol parse error | Ruby could not decode the renderer response. | Raise a prerender error without exposing the raw response. |
The Ruby helper turns a result with hasErrors into PrerenderError only when the configured error policy requires it. In streaming mode, shell readiness selects the policy for non-shell errors versus later errors. Connection detection checks wrapped causes and narrow renderer transport messages, while an existing bundle-load error remains a bundle error. References: react_on_rails/…/helper.rb• L898-963, react_on_rails/…/helper.rb• L1001-1025, react_on_rails/…/ruby_embedded_java_script.rb• L23-46, react_on_rails/…/ruby_embedded_java_script.rb• L261-336
Diagnostic context
PrerenderError reports the component, error details, JavaScript code, props, and console output in a form that helps diagnose a failed render. Props and generated code are redacted in the error object because these values can contain application data. Parse errors receive a safe summary instead of the raw response body. Renderer connection messages also sanitize configured or observed URLs, including malformed configured URLs and passwords containing @, before they enter logs or error reports.
The error message can also suggest a likely fix for common server-only mistakes such as use of window, document, undefined props, or a server and client hydration mismatch. Full JavaScript backtraces are available only when the related diagnostic setting enables them.
References: react_on_rails/…/prerender_error.rb• L7-25 react_on_rails/…/prerender_error.rb• L36-74 react_on_rails/…/prerender_error.rb• L123-181 react_on_rails/…/ruby_embedded_java_script.rb• L308-443
Node execution errors
The Node worker converts exceptions from bundle evaluation into a render result that the renderer boundary can report. It also observes errors emitted by a readable render stream. Errors from the VM keep their useful message and source-mapped stack when possible, even though they come from a separate JavaScript realm. References: packages/…/vm.ts• L1022-1059, packages/…/vm.ts• L1075-1087
TypeScript response contracts
The response type registry is a separate contract from the server-rendering wire envelope. It describes JSON responses returned by Rails actions so TypeScript code can use the same named response shapes as the Rails side.
Response type registry
Rails code registers a response key, a TypeScript type name, and a field shape with ReactOnRails::TypeScriptResponseTypes. The registry supports shared named types and nested objects, arrays, nullable fields, optional fields, JSON values, and safe raw TypeScript expressions.
Names and response keys must be unique. Type names must be valid identifiers and cannot replace built-in or generated names. Invalid field shapes and unsafe raw expressions fail during registration or declaration generation rather than producing a misleading client contract.
References: react_on_rails/…/typescript_response_types.rb• L215-240 react_on_rails/…/typescript_response_types.rb• L297-375 react_on_rails/…/typescript_response_types.rb• L434-503
Declaration generation
The react_on_rails:generate_response_types task emits a .d.ts file inside Rails.root. The file contains shared JSON types, registered interfaces, a RailsResponseTypes map, and generic helpers that map a response key to its TypeScript response type.
The writer creates the output safely and rejects paths outside the Rails application root. Generated files carry a header that marks them as derived output. Applications should change the Ruby registrations and regenerate the declaration rather than edit the declaration by hand. References: react_on_rails/lib/tasks/generate_response_types.rake#L5-L13, react_on_rails/…/typescript_response_types.rb• L224-232, react_on_rails/…/typescript_response_types.rb• L377-419, react_on_rails/…/generated_file_writer.rb• L19-33
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the JavaScript envelope fields aligned between
RenderResult,buildRenderMetadata, and Ruby result consumers. - Keep the length prefix as a UTF-8 byte count. Character counts can break responses that contain emoji or other multi-byte text.
- Keep
payloadTypehandling aligned between the JavaScript encoder andLengthPrefixedParser. - Keep
propRequestandrenderCompletecontrol values aligned across the Ruby parser, the Pro stream reader, and the Node renderer. - When changing stream error policy, review both shell-ready and non-shell-ready paths in the Rails helper.
- When changing response type names or field rules, review the registry validation, emitter output, generated declaration, and Rails action contract together.
- When changing the renderer pool boundary, preserve the same Ruby call and error distinction for embedded and Node renderers.
- When changing bundle source loading, preserve declared-character-set decoding, UTF-8 validation, and credential-free error messages for both valid and malformed URLs.
- When changing renderer connection detection, preserve cause-chain checks and avoid treating in-process bundle errors as transport failures.
- When changing Node VM pool limits or bundle rollout rules, review readiness, generation draining, request-local state, and source-map lifetime together.
- When changing Node VM error handling, preserve error identity and source-map remapping for both direct execution and stream failures.
- When changing store hydration scope or lookup behavior, preserve the separation between request-scoped stores, the fallback map, and named store-generator registration.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| The server bundle does not expose the render API selected by the generated request. | Ruby receives a JavaScript evaluation error instead of component HTML. | Keep bundle entry points and render-mode selection aligned. |
| A remote server bundle uses a character set that does not match its bytes. | Bundle loading fails before evaluation instead of silently running corrupted source. | Serve the correct charset and keep UTF-8 validation enabled. |
Credentials remain in a bundle or renderer URL error, including a password with @ in a malformed configured URL. | Passwords can reach Rails logs or error trackers. | Use the bridge's URL sanitization for normal and malformed URLs before formatting errors. |
| The length prefix counts characters instead of UTF-8 bytes. | Ruby reads too few or too many bytes and reports a malformed or truncated response. | Use the UTF-8 byte length when encoding every non-streaming and streaming payload. |
| Metadata or object payload JSON is malformed. | Ruby cannot recover render state or HTML and raises a parse-focused prerender error. | Keep the strict length-prefixed parser and lenient JSON behavior in sync with the JavaScript encoder. |
| A separate Node renderer is down or its host and port do not match Rails configuration. | No component code runs and the request fails as a renderer connection error. | Check the renderer process and configured target before debugging component registration. |
| A streamed render fails after content has reached the client. | Retrying could duplicate page content. | Retry transport failures only before the first content chunk. |
| A response type key or TypeScript name is duplicated. | Declaration generation fails or a client contract becomes ambiguous. | Register unique keys and names through the response type registry. |
A generated response declaration path is outside Rails.root. | The generation task refuses to write the file. | Use an output path inside the Rails application. |
| The Node worker evicts a bundle context while a request still uses its source map. | Error stacks can lose source locations or cleanup can affect a live request. | Retain source-map registrations until each request releases them. |
| A new bundle generation replaces the declared current generation before it is ready. | Readiness or render routing can point at an incomplete bundle set. | Prewarm the declared generation and keep older generations draining until retirement. |
| Request-shared state remains attached to a reusable VM after execution. | Data from one render can become visible to another request. | Inject request state only during execution and remove the VM reference immediately afterward. |
| A render reads a store outside its active hydration scope. | The component can see missing or stale store data. | Keep scoped store lookup available and hydrate the expected store name before rendering. |
Key files
| File | Why to read it |
|---|---|
| react_on_rails/…/helper.rb | Rails-side request setup, response consumption, stream error policy, and HTML return path. |
| react_on_rails/…/render_options.rb | Per-render policy for prerendering, hydration, error handling, and render mode. |
| react_on_rails/…/server_rendering_pool.rb | Shared Ruby pool boundary used by Rails helpers. |
| react_on_rails/…/ruby_embedded_java_script.rb | Embedded execution, bundle loading, result format detection, connection errors, URL sanitization, and console replay. |
| react_on_rails/…/server_rendering_js_code.rb | Base JavaScript request expression generated for a component render. |
| react_on_rails/…/length_prefixed_parser.rb | Shared wire format parser for complete and streamed results. |
| packages/…/serverRenderReactComponent.ts | JavaScript render result creation and error state production. |
| packages/…/serverRenderUtils.ts | Shared metadata and length-prefixed response encoding. |
| packages/…/index.ts | TypeScript shapes for render results and Rails server-render APIs. |
| packages/…/StoreRegistry.ts | Store generator registration and request-aware hydrated-store lookup used by rendered components. |
| react_on_rails/…/prerender_error.rb | Error message and diagnostic context for failed server renders. |
| react_on_rails/…/typescript_response_types.rb | Ruby registry and declaration emitter for Rails JSON response contracts. |
react_on_rails/lib/tasks/generate_response_types.rake | Rails task that writes generated response declarations. |
| react_on_rails_pro/…/node_rendering_pool.rb | Pro Node renderer boundary and stream selection. |
| react_on_rails_pro/…/stream_request.rb | Pro stream consumption and routing of control messages. |
| packages/…/vm.ts | Pro worker VM reuse, bundle generations, request isolation, readiness, and execution error handling. |