Introducing a new way to review your PRs.

Read the announcement

shakacode / react_on_rails

Integration of React + Webpack + Rails including server-side rendering of React, enabling a better developer experience and faster client performance.

View on GitHub

19 documents · Updated Nov 18, 2026

docs / node-renderer-processes

Node renderer processes and integrations

The Pro Node renderer is the service that runs server-side JavaScript for React on Rails. Rails sends render work and, when needed, bundle files to the service over HTTP. The service runs that work in worker processes and returns HTML or a stream. The same boundary carries health checks, asset uploads, errors, and optional tracing data.

This page is a child of Pro rendering platform. Read Async props and streaming SSR for the wider streaming flow, Renderer cache and rolling deploys for artifact life cycle, Pro licensing and observability for operational controls, Server rendering protocol for the wire contract, React Server Components for the RSC model, and RSC request and rendering flow for the RSC request path.

Renderer process topology

The renderer starts as either one process or a master process with a set of workers. The master owns worker life cycle and recovery. Each worker owns the HTTP server and handles render requests, so a worker failure does not require the service to lose all capacity.

The normal process shape is:

flowchart TD
    launcher[Renderer launcher] --> mode{Worker count}
    mode -->|0| single[Single worker process]
    mode -->|greater than 0| master[Master process]
    master --> workers[Worker processes]
    workers --> http[HTTP render service]
    http --> result[HTML or stream]

The master replaces an unexpected worker exit and can also replace workers on a planned schedule. Planned restarts shut down workers one at a time, which keeps the remaining workers available. A startup failure stops the cluster and reports the failure to the process supervisor. A shutdown signal drains workers, avoids re-forking them, and force-stops a blocked worker before the master exits.

References: packages/…/master.ts• L104-359 packages/…/restartWorkers.ts• L34-132

Worker readiness

Each worker checks its runtime and prepares the current renderer generation before it accepts traffic when a generation manifest is configured. The health endpoint shows that the process is alive. The readiness endpoint shows whether a usable renderer context is available or every bundle in the declared current generation is compiled and retained.

The declared current generation is prewarmed as one set. Its size must fit within the VM pool limit. Older generations can remain available during a rollout, but pressure cannot evict the declared current set to serve an older request. If an older request cannot enter the shared pool, it keeps a request-scoped context until release. A worker's readiness therefore reflects the complete current set, not only one compiled bundle.

Workers also expose extension points before the HTTP server starts. This lets an integration add server hooks and shutdown work without taking ownership of the renderer life cycle.

References: packages/…/worker.ts• L629-674 packages/…/worker.ts• L1483-1566 packages/…/startCurrentGeneration.ts• L1-120 packages/…/shutdownHooks.ts• L1-140 packages/…/vm.ts• L382-445 packages/…/vm.ts• L1105-1155

Renderer HTTP API

The renderer API accepts a render request that names a bundle generation and contains executable render code. It supports a regular request for a complete result and a streaming request for output that becomes available over time. Rails can send the bundle and companion assets in the same request when a worker does not have them.

The main request paths are:

RequestPurposeResult
POST /bundles/:bundleTimestamp/render/:renderRequestDigestRun one render requestA complete value or a one-way output stream
POST /bundles/:bundleTimestamp/incremental-render/:renderRequestDigestRun a render with later async prop updatesA streamed result while Rails sends NDJSON updates
POST /upload-assetsPopulate renderer bundle and asset storageUpload status
POST /asset-existsCheck an asset across target bundlesPer-bundle existence results
GET /healthCheck that the HTTP service respondsStatic health status
GET /readyCheck that the worker can serve rendersReady status or retry response
GET /infoReport renderer and Node versionsVersion information

The request body can use a multipart form for bundle uploads or a compact raw format for a render that reuses an existing bundle. The renderer authenticates protected requests before it writes uploaded files. It validates bundle references and limits before execution. Health and readiness probes are opt-in and do not require the renderer password so that process supervisors can call them.

References: packages/…/worker.ts• L594-705 packages/…/worker.ts• L761-872 packages/…/worker.ts• L1332-1527 packages/…/authHandler.ts• L17-69

Render request flow

The renderer first checks the request and looks for an execution context for the requested bundle set. On a miss it accepts the uploaded bundle or confirms that the bundle is already present. It then creates the context, runs the render code, and maps the result to an HTTP response.

This diagram shows how a Rails render becomes a result at the Node boundary.

sequenceDiagram
    participant Rails
    participant Worker
    participant BundleStore as Bundle and asset store
    participant VM as Render execution context

    Rails->>Worker: Render request and optional uploads
    Worker->>Worker: Authenticate and validate request
    Worker->>BundleStore: Store missing bundle and assets
    Worker->>VM: Reuse or build context
    VM-->>Worker: Value, error, or stream
    Worker-->>Rails: HTTP result or streamed chunks

A render result uses a status, headers, and either a value or a stream. Errors become non-cacheable responses and include a bounded description of the render failure. A client disconnect destroys an unfinished render stream, which releases the execution context and stops work that has no downstream reader.

References: packages/…/handleRenderRequest.ts• L286-422 packages/…/worker.ts• L207-326 packages/…/utils.ts• L63-119 packages/…/utils.ts• L242-259

RSC stream handoff

RSC rendering uses the same stream boundary as progressive SSR. The Node result carries framed payload data and response metadata to the Pro rendering path, which makes the payload available to the page while HTML arrives. The HTML stream keeps payload setup ahead of component markup and places later payload data after that markup so the browser can consume both in order.

When client-component styles are known, the handoff can place their stylesheet links before a streamed reveal. If the optional loadable-stats.json file is missing or not ready, the Pro path keeps the render working and uses its streamed preload fallback while it retries the read. The Node VM reports the missing file through a protected host diagnostic instead of exposing request state to other renders.

References: packages/…/injectRSCPayload.ts• L126-206 packages/…/injectRSCPayload.ts• L1620-1672 packages/…/injectRSCPayload.ts• L1730-1894 packages/…/injectRSCPayload.ts• L1990-2210 packages/…/vm.ts• L63-80

Worker execution model

The worker runs each bundle in an isolated JavaScript context and keeps reusable contexts for later requests. An execution context groups the bundle contexts needed by one request and provides request-local shared state. This state allows a later render action to continue the same request without using process-global data.

The context lifetime follows the response. A complete result releases its context after execution. A stream keeps it until the stream ends or the client abandons it. Bundle generations can retire old contexts after a deployment while active requests retain the resources they still need.

The VM pool has an absolute context limit. It prefers contexts from the declared current generation and removes older least-recently-used contexts under pressure. Generation retirement waits for the rollout drain period. This lets old and new bundle sets overlap without allowing rollout traffic to grow the pool without bound.

References: packages/…/vm.ts• L70-115 packages/…/vm.ts• L271-380 packages/…/vm.ts• L516-573 packages/…/vm.ts• L861-943 packages/…/vm.ts• L1060-1127

Bundle execution

The worker treats the bundle identifier as the identity of the code and its related files. It can combine an entry bundle with dependency bundles, then reuse a matching context. A missing bundle produces a request error rather than an attempt to run unknown code.

The render code selects the React render operation for the request. It can return HTML, a React server component payload, or a readable stream. The Ruby side supplies the render expression and the context that tells it which component and props to use.

References: packages/…/handleRenderRequest.ts• L304-355 packages/…/handleRenderRequest.ts• L383-414 react_on_rails_pro/…/server_rendering_js_code.rb• L106-166

Incremental render execution

Incremental rendering is the bidirectional form of streaming SSR. Rails sends the first NDJSON line with the render request. The worker starts the render and returns the initial output stream. Rails then sends update lines as async values become available, and the worker applies each update in the same execution context.

The stream reader limits the full request and each line. A malformed first line stops the request. A malformed later update is reported and skipped so later updates can still arrive. Each accepted update yields to the event loop, which lets React flush a separate stream chunk. The sequence ends when Rails closes its request body, or when the pull-mode response has no progress for its idle limit. The worker uses that end signal to close the async prop channel and release the execution context.

References: react_on_rails_pro/…/request.rb• L120-203 packages/…/worker.ts• L874-1330 packages/…/handleIncrementalRenderStream.ts• L22-329

Integration adapters

Integration adapters connect the renderer to error reporting and tracing services without placing a service SDK in the core request path. The public integration API also lets an adapter add Fastify setup and worker shutdown work. The default callbacks do nothing, so the renderer remains usable without an adapter.

Supported adapter roles include:

Adapter roleSystem effect
Error notifierSends renderer errors and messages to a monitoring service
Request tracingWraps an SSR request in the service's unit of work
Sub-span tracingReports bundle work and render stages inside the request
HTTP server hookAdds service-specific request or error handling
Shutdown hookFlushes service state before a worker exits

The public integration surface is packages/…/api.ts. Sentry and Honeybadger adapt error and request handling. OpenTelemetry can create a renderer-owned provider or attach to an existing global provider. Only one tracing adapter and one sub-span adapter can own the shared tracing hooks at a time.

References: packages/…/api.ts• L16-78 packages/…/fastifyConfig.ts• L1-100 packages/…/shutdownHooks.ts• L1-140 packages/…/sentry.ts• L16-62 packages/…/sentry6.ts• L16-67 packages/…/honeybadger.ts• L16-43 packages/…/opentelemetry.ts• L51-85

OpenTelemetry ownership

OpenTelemetry setup is optional and loads its SDK only when initialization needs it. In renderer-owned mode, the renderer creates the provider, chooses a span processor, registers optional HTTP and Fastify instrumentation, and cleans up those resources during worker shutdown. A caller-supplied provider or processor keeps its ownership rules.

Existing-provider mode uses the host application's global provider and API context. The host must register a real tracer provider and a working context manager before the renderer attaches its SSR and sub-span adapters. The renderer does not load a second SDK or shut down the host provider. If the provider is not ready, initialization warns and remains retryable. Duplicate initialization is ignored.

Service identity follows this order: OTEL_SERVICE_NAME, the serviceName option, explicit service.name resource attributes, and then the default renderer name. Resource detectors add other attributes below explicit configuration. Detector failures omit unavailable attributes and do not stop rendering.

Instrumentations are disabled before provider shutdown. The shutdown wait is capped below the worker's forced-shutdown limit, so tracing cleanup cannot hold a worker past the process drain deadline. A failed initialization also removes partial global state and installed instrumentation.

References: packages/…/opentelemetryConfig.ts• L16-175 packages/…/opentelemetry.ts• L87-121 packages/…/opentelemetry.ts• L295-342 packages/…/opentelemetry.ts• L380-565

Shared tracing contract

The tracing layer defines a small contract around an SSR request and its child units of work. An integration supplies the function that starts and ends its span or transaction. The renderer supplies safe stage names and counts such as bundle work and response size instead of raw request payloads.

Tracing is optional and has a pass-through mode. If an adapter fails before it calls the wrapped work, the renderer still runs the work without tracing. This keeps observability from changing render behavior.

References: packages/…/tracing.ts• L19-107 packages/…/tracing.ts• L133-220 packages/…/handleRenderRequest.ts• L322-377

Shared protocol utilities

Shared protocol utilities keep the Ruby client and Node worker aligned on request fields, response shapes, bundle files, and stream behavior. They also centralize input checks and error formatting so each endpoint follows the same rules.

The most important shared contracts are:

  • Bundle identifiers select the code and companion assets for a render.
  • renderingRequest is the executable render expression sent from Ruby to Node.
  • A response contains a status and headers plus either data or a stream.
  • Incremental requests use NDJSON for the first request and later updates.
  • Raw render metadata moves through controlled HTTP headers rather than a large form body.

The utilities also protect the boundary. They reject unsafe asset names, cap diagnostic snippets, clean up stream errors, and keep error responses from being treated as cacheable render output.

References: packages/…/utils.ts• L30-119 packages/…/utils.ts• L136-206 packages/…/workerMessages.ts• L16-45 react_on_rails_pro/…/request.rb• L323-368

Ruby rendering boundary

The Ruby rendering pool is the application-facing side of the renderer. ProRendering chooses the Node pool when Node rendering is enabled and otherwise uses the embedded Ruby JavaScript path. The pool turns React render options into a request path and delegates execution to the Ruby request client.

For Node rendering, the pool selects the server or RSC bundle role. It sends a complete render, a one-way stream, or a bidirectional incremental stream based on the render options. It can also fall back to embedded execution when that option is enabled and the Node request fails.

References: react_on_rails_pro/…/pro_rendering.rb• L16-45 react_on_rails_pro/…/node_rendering_pool.rb• L53-135 react_on_rails_pro/…/node_rendering_pool.rb• L154-210

Ruby HTTP client

RendererHttpClient is the transport boundary between Rails and the Node service. It supports form, JSON, raw, one-way streaming, and bidirectional streaming requests. It reuses connections where the Ruby runtime supports a long-lived scheduler and closes them when the rendering pool resets.

The client turns connection and timeout faults into typed errors. The request layer can retry those transport faults within its configured limit. It does not hide protocol failures: an incompatible renderer response is fatal, while a missing bundle response tells the caller to upload and retry.

When a Ruby OpenTelemetry provider is configured, the client creates a client span for the renderer request and propagates only the trace context headers. It records method, normalized path, status, and byte counts. It excludes render code, props, response text, bundle identifiers, and query values from span attributes. A streaming span ends only after the request body and response have both finished. The bundle-upload status used to request a retry is not treated as a client error.

References: react_on_rails_pro/…/renderer_http_client.rb• L235-300 react_on_rails_pro/…/renderer_http_client.rb• L491-703 react_on_rails_pro/…/request.rb• L247-300 react_on_rails_pro/…/open_telemetry.rb• L30-128 react_on_rails_pro/…/open_telemetry.rb• L146-202

Bundle and asset transfer

The Ruby side sends bundle bytes and companion files only when the Node side needs them. A render request can carry the files in multipart form. A raw render request carries only the render code and metadata when the bundle is already present.

The Node worker stores each upload in a request-specific directory before it moves the bundle into its generation location. A lock makes concurrent uploads for the same generation safe. Cleanup runs after the response and the master removes old upload directories left by failed workers.

References: react_on_rails_pro/…/request.rb• L93-99 react_on_rails_pro/…/request.rb• L376-411 packages/…/handleRenderRequest.ts• L175-279 packages/…/master.ts• L78-102

Rolling-deploy artifact boundary

The built-in rolling-deploy HTTP adapter lets the next deployment fetch bundle artifacts from a currently running Rails server. The running server is the artifact source, so the adapter needs no separate object store. It discovers available bundle identities through an authenticated manifest request and fetches each selected bundle as a compressed archive with its companion assets.

The adapter accepts more than one previous server for failover. It filters unsafe origins and hashes before making requests. Versioned artifact identities are checked again after download. Ambiguous legacy identities are omitted when more than one origin advertises them because the bytes cannot prove which artifact was intended. Upload is intentionally a no-op: the current server already has the files on disk.

The fetch path has connection, read, total-operation, compressed-body, and extracted-size limits. HTTPS uses peer verification. Plain HTTP is allowed for local use but warns when a bearer token would cross a non-loopback network. A failed seed logs a warning and returns no artifact, so runtime 410 retry behavior remains the fallback instead of making the build fail.

References: react_on_rails_pro/…/http.rb• L31-84 react_on_rails_pro/…/http.rb• L86-137 react_on_rails_pro/…/http.rb• L141-273 react_on_rails_pro/…/http.rb• L374-545

Renderer package compatibility

The Node renderer package exposes the renderer, master, worker, and public integration entry points. Its package contract requires Node 20.19 or later and keeps internal integration modules private. Optional monitoring and tracing SDKs remain peer dependencies, so an application selects only the integrations it uses.

RSC peer compatibility is checked only when react-on-rails-rsc is present. The check accepts stable React Server Components package and React pairs that share the same Flight line:

RSC package lineRequired React and React DOM line
19.2.1 and later 19.2.x19.2.7 or later
19.3.019.2.8 or later
19.3.119.3.0 or later
19.3.2 and later 19.3.x19.3.1 or later

The compatibility boundary rejects unsupported majors, unsupported minor or patch pairs, prerelease versions, and mismatched react and react-dom versions. It can name a known stable successor for superseded prerelease lines, but it does not assume that every compatible prerelease has been published.

The packed compatibility check builds the core and Pro artifacts, installs them in isolated consumers, and runs the Node SSR API against selected React versions. It also confirms the progressive streaming result where that React version supports it. For versions without server streaming, the same SSR API remains the fallback. Non-RSC consumers must not pull the optional RSC package into their install or bundle graph.

References: packages/…/package.json• L4-31 packages/…/package.json• L86-136 packages/…/rscPeerSupport.ts• L16-55 packages/…/checkRscPeerCompatibility.ts• L177-261 packages/…/checkRscPeerCompatibility.test.ts• L30-327 packages/…/package.json• L1-19 packages/…/package.json• L36-108 packages/…/packed-react-compatibility-manifest.mjs• L16-33 packages/…/packed-react-compatibility-smoke.mjs• L292-360 packages/…/install-and-upgrade.md• L93-112

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the Ruby request body fields and raw metadata headers aligned with the Node worker's request normalizer.
  • Keep the server and RSC bundle role rules aligned across render-path creation, upload fields, and worker bundle lookup.
  • Keep incremental NDJSON field names and async-props bridge behavior aligned with the browser-side async props manager.
  • Keep worker shutdown-hook limits below the master drain deadline so integrations can flush before forced termination.
  • Keep HTTP status handling aligned between the Node response contract and Ruby retry, upload, and stream callers.
  • Keep OpenTelemetry service-name precedence and resource-detector merging aligned between the Node provider and Ruby client spans.
  • Keep existing-provider mode separate from renderer-owned provider mode. The host owns SDK setup and shutdown in the former.
  • Keep VM pool admission, declared-current readiness, and generation drain rules aligned with rolling-deploy prewarming.
  • Keep the mirrored missing-loadable-stats.json diagnostic key aligned between the Node VM and the Pro RSC stream path.
  • Keep rolling-deploy artifact identity, archive entry names, origin validation, and size limits aligned with the serving Rails controller.
  • Keep the Node renderer's public export paths and optional peer ranges aligned with the package consumers that load integrations.
  • Keep the RSC support table, Ruby Doctor mirror, and compatibility messages aligned when a React or react-on-rails-rsc release changes.

Important failure modes

TriggerConsequenceGuard
Node and Ruby protocol versions do not matchRequests fail at the compatibility boundaryRun the peer compatibility check and treat the incompatible status as fatal
RSC, React, or React DOM versions do not share a supported stable pairRSC startup reports an incompatible peer error before renderingUse one supported version row and keep react and react-dom on the same version
A render names a missing or over-limit bundle setThe worker returns a non-cacheable error and does not execute the requestUpload the matching artifact set and keep the VM pool limit above the request's bundle count
The declared current generation needs more contexts than maxVMPoolSizeStartup cannot make the worker ready for that generationSize the VM pool for the complete declared bundle set
A worker reports a startup failureThe master stops the cluster and exits non-zero instead of replacing the workerCheck the startup error and let the process supervisor restart the service after the cause is fixed
A worker dies during normal operationThe master reports the crash and starts a replacement workerUse the master process as the service entry point
A multipart request has a wrong password or unsafe file nameThe request is rejected before the upload can be usedAuthenticate before file persistence and validate each filename
Rails closes an incremental request before all props arriveThe worker ends the async prop stream and pending values can failTreat request-body close as the end of the producer stream
The first incremental NDJSON object is malformedThe render does not startSend a valid first object before update objects
A client or proxy interrupts a render streamUpstream work can remain active without stream teardownPropagate response close to the renderer stream and release the execution context
The renderer connection times out or is refusedRuby retries until its limit, then raises a renderer errorSet transport timeouts and a retry limit that match the service topology
An existing OpenTelemetry provider has no usable context managerRenderer spans are not installed even though the provider existsRegister the host provider with its context manager before renderer initialization
OpenTelemetry instrumentation setup fails part way throughPartial patches or global provider state can affect later workDisable created instrumentations and clear renderer-owned globals during rollback
A detector fails while resolving OpenTelemetry resourcesIts attributes are absent from spansTreat detector errors as optional metadata and inspect the warning
The VM pool is full of declared-current contexts during an old-generation requestThe old context stays request-scoped and does not enter the shared poolKeep the current generation within the hard pool limit and release old requests
loadable-stats.json is missing or malformedRSC stylesheet inference is unavailable and streamed preload fallback is usedShip the file with the renderer bundle when inference is needed; allow the retry path to recover
A rolling-deploy origin or hash is unsafeThe adapter skips the origin or artifact without making the requestUse HTTPS origins with safe paths and a configured bearer token
Multiple origins advertise the same legacy artifact hashThe adapter omits that hash because its identity is ambiguousUse versioned artifact identities or one origin for legacy hashes
A rolling-deploy response exceeds compressed or extracted size limitsThe download is aborted and temporary files are removedKeep bundles within the configured archive limits and preserve archive entry names

Key files

FileWhy to read it
packages/…/ReactOnRailsProNodeRenderer.tsShows the service entry choice between single-process and master-worker modes
packages/…/master.tsDefines worker creation, replacement, startup-failure aborts, and shutdown behavior
packages/…/restartWorkers.tsShows the sequential graceful restart used for scheduled worker replacement
packages/…/worker.tsDefines the HTTP boundary, request routes, health checks, stream cleanup, and response handling
packages/…/handleRenderRequest.tsShows bundle admission, context reuse, and render execution at a high level
packages/…/handleIncrementalRenderRequest.tsExplains the shared execution context used for async prop updates
packages/…/handleIncrementalRenderStream.tsExplains NDJSON input, chunk limits, update handling, and stream end behavior
packages/…/vm.tsDefines isolated execution contexts, pool limits, generation retention, and readiness
packages/…/api.tsLists the public extension points for monitoring, server setup, and worker life cycle hooks
packages/…/opentelemetry.tsDefines renderer-owned and existing-provider tracing setup and cleanup
packages/…/opentelemetryConfig.tsDefines service identity and resource detector precedence
packages/…/tracing.tsDefines the shared tracing and sub-span contract
packages/…/rscPeerSupport.tsDefines the supported stable RSC and React version pairs
packages/…/checkRscPeerCompatibility.tsApplies the RSC peer contract before the RSC renderer path runs
packages/…/checkRscPeerCompatibility.test.tsShows the supported floor, version pair rules, and prerelease failures
packages/…/injectRSCPayload.tsShows the RSC payload and stylesheet handoff into the HTML stream
react_on_rails_pro/…/pro_rendering.rbSelects the Node or embedded Ruby rendering path
react_on_rails_pro/…/node_rendering_pool.rbMaps Ruby render options to Node endpoints and bundle roles
react_on_rails_pro/…/request.rbBuilds render, upload, raw, and incremental requests
react_on_rails_pro/…/renderer_http_client.rbImplements the Ruby HTTP and streaming transport boundary
react_on_rails_pro/…/open_telemetry.rbAdds trace propagation and safe byte-level spans around renderer HTTP calls
react_on_rails_pro/…/http.rbFetches and validates prior deployment artifacts over authenticated HTTP
packages/…/package.jsonDefines the Node server export and package compatibility surface
packages/…/packed-react-compatibility-smoke.mjsVerifies packed SSR and streaming behavior in isolated React consumers