universal_renderer 0.5.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -4,221 +4,500 @@
4
4
 
5
5
  [![Gem Version](https://img.shields.io/gem/v/universal_renderer)](https://rubygems.org/gems/universal_renderer) [![NPM Version](https://img.shields.io/npm/v/universal-renderer)](https://www.npmjs.com/package/universal-renderer)
6
6
 
7
- A streamlined solution for integrating Server-Side Rendering (SSR) into Rails applications.
7
+ Server-Side Rendering for Rails apps with a React front end.
8
8
 
9
9
  ## Overview
10
10
 
11
- UniversalRenderer helps you forward rendering requests to external SSR services, manage responses, and improve performance, SEO, and user experience for JavaScript-heavy frontends. It works seamlessly with the `universal-renderer` NPM package.
11
+ UniversalRenderer runs your React app in a small Node/Bun service and splices the
12
+ result into your Rails layout. It is two halves of one contract: the
13
+ `universal_renderer` gem talks to the `universal-renderer` NPM package.
12
14
 
13
- ## Features
15
+ The design assumption is retrofitting: you have a working client-rendered app,
16
+ you want the first paint to be server-rendered, and you cannot afford for SSR to
17
+ become a source of outages. So every failure path — service down, timeout, 500,
18
+ not configured — falls back to client-side rendering silently, and the
19
+ instrumentation exists so "silently" does not mean "invisibly".
14
20
 
15
- - **Streaming SSR** support
16
- - **Configurable SSR server endpoint** and timeouts
17
- - **Simple API** for passing data between Rails and your SSR service
18
- - **Automatic fallback** to client-side rendering if SSR fails
19
- - **View helpers** for easy integration into your layouts
21
+ ### Version compatibility
22
+
23
+ The two packages share a wire format, so upgrade them together.
24
+
25
+ | Gem | NPM package | Notes |
26
+ | ------- | ----------- | --------------------------------------------------------------------- |
27
+ | `0.8.x` | `0.8.x` | Puma plugin replaces `bin/web`; self-contained, production SSR builds |
28
+ | `0.7.x` | `0.7.x` | `payload`, conditional `enable_ssr`, `concurrency`, `prepare` |
29
+ | `0.5.x` | `0.6.x` | |
20
30
 
21
31
  ## Installation
22
32
 
23
- 1. Add to your Gemfile:
33
+ ```ruby
34
+ # Gemfile
35
+ gem "universal_renderer"
36
+ ```
24
37
 
25
- ```ruby
26
- gem "universal_renderer"
27
- ```
38
+ ```bash
39
+ bundle install
40
+ bun add universal-renderer # or npm / yarn
41
+ bin/rails generate universal_renderer:install
42
+ ```
28
43
 
29
- 2. Install:
44
+ The generator writes the initializer, the two renderer entry points, the SSR Vite
45
+ build, and the `assets:precompile` hook, and adds `plugin :universal_renderer` to
46
+ `config/puma.rb` to run the renderer in production. Pass
47
+ `--frontend-dir=app/client` if your JavaScript is not in `app/frontend`.
30
48
 
31
- ```bash
32
- $ bundle install
33
- ```
49
+ ## Rendering from a controller
34
50
 
35
- 3. Run the generator:
51
+ There are two ways in, and they are equally supported.
36
52
 
37
- ```bash
38
- $ rails generate universal_renderer:install
39
- ```
53
+ **Declarative**, when the whole action is server-rendered:
40
54
 
41
- ## Configuration
55
+ ```ruby
56
+ class ArticlesController < ApplicationController
57
+ enable_ssr only: :show, unless: -> { current_user.present? }
58
+
59
+ def show
60
+ @article = Article.find(params[:id])
61
+ add_query_data(["articles", @article.slug], article_json)
62
+ render "common/js_only"
63
+ end
64
+ end
65
+ ```
42
66
 
43
- Configure in `config/initializers/universal_renderer.rb`:
67
+ `enable_ssr` takes `only:`, `except:`, `if:`, and `unless:` (Symbol or Proc,
68
+ evaluated against the controller), plus `streaming: true`.
69
+
70
+ **Imperative**, when the decision or the data depends on request state:
44
71
 
45
72
  ```ruby
46
- UniversalRenderer.configure do |c|
47
- c.url = "http://localhost:3001"
48
- c.timeout = 3
49
- c.stream_path = "/stream"
50
- c.http.pool_size = 5 # persistent Net::HTTP connections per SSR origin
73
+ def show
74
+ @article = Article.find(params[:id])
75
+ return render("common/js_only") unless public_view?
51
76
 
52
- # Blocking SSR is the default. Enable streaming per controller only when needed:
53
- # enable_ssr streaming: true
77
+ add_query_data(["articles", @article.slug], article_json)
78
+ add_prop(:feature_flags, enabled_flags)
79
+ render_ssr
80
+
81
+ render "common/js_only"
54
82
  end
55
83
  ```
56
84
 
57
- The gem itself never reads environment variables; it only exposes the plain
58
- configuration attributes above with sensible defaults. Binding those values to
59
- `ENV` is entirely up to you, in your own initializer, using whatever keys you
60
- like. If you want a convention, the suggested env-var prefix is
61
- `UNIVERSAL_RENDERER_*` (e.g. `UNIVERSAL_RENDERER_URL`):
85
+ `render_ssr` fetches once, memoizes, and returns the payload — or `nil`, which is
86
+ your signal to let the client-rendered path stand. It works whether or not the
87
+ controller called `enable_ssr`.
88
+
89
+ ### Props
90
+
91
+ | Method | Effect |
92
+ | ------------------------------- | --------------------------------------------------------------- |
93
+ | `add_prop(key, value)` | Sets one prop. Also takes a hash. |
94
+ | `push_prop(key, value)` | Appends to an array prop. |
95
+ | `add_query_data(key, data)` | Adds a React Query cache entry under the `react_query` prop. |
96
+ | `ssr_props` | The accumulated hash, if you need to inspect or merge it. |
97
+
98
+ ## Rendering in the layout
99
+
100
+ ```erb
101
+ <head>
102
+ <%= ssr_head %>
103
+ <%= ssr_payload %>
104
+ </head>
105
+ <body class="app" <%= ssr_body_attributes %>>
106
+ <div id="root"><%= ssr_body %></div>
107
+
108
+ <%# Server-rendered pages hydrate; everything else boots a client render. %>
109
+ <%= vite_typescript_tag ssr? ? "hydrate.tsx" : "application.tsx" %>
110
+ </body>
111
+ ```
112
+
113
+ Every helper is a no-op when there is nothing to emit, so the layout needs no
114
+ conditionals. `ssr?` is there for the decisions that are not about emitting HTML —
115
+ picking an entry point, skipping a preload — and it never requires reading an
116
+ instance variable. It is true for streamed pages too, which are server-rendered
117
+ even though the payload arrives after the layout.
118
+
119
+ `ssr_payload` emits whatever your `render` callback returned as `payload`, as an
120
+ inert `<script type="application/json">`, escaped. That is the channel for
121
+ hydration state, because the interesting state is only known after the render: a
122
+ dehydrated query cache, the class names a CSS-in-JS library already wrote into
123
+ `head`. Do not hand-roll a script tag inside `head`.
124
+
125
+ ## Configuration
62
126
 
63
127
  ```ruby
64
128
  UniversalRenderer.configure do |c|
65
129
  c.url = ENV.fetch("UNIVERSAL_RENDERER_URL", "http://localhost:3001")
66
- c.timeout = ENV.fetch("UNIVERSAL_RENDERER_TIMEOUT", 3).to_i
67
- # ...
130
+ c.timeout = 3
131
+ c.stream_path = "/stream" # must match the Node side's `paths`
132
+ c.http.pool_size = 5
68
133
  end
69
134
  ```
70
135
 
71
- ## Setting Up the SSR Server
72
-
73
- To set up the SSR server for your Rails application:
74
-
75
- 1. Install the NPM package in your JavaScript project:
76
-
77
- ```bash
78
- $ npm install universal-renderer
79
- # or
80
- $ yarn add universal-renderer
81
- ```
82
-
83
- 2. Create a `setup` function at `app/frontend/ssr/setup.ts`:
84
-
85
- ```tsx
86
- import {
87
- HelmetProvider,
88
- type HelmetDataContext,
89
- } from "@dr.pogodin/react-helmet";
90
- import { QueryClient, QueryClientProvider } from "react-query";
91
- import { StaticRouter } from "react-router";
92
- import { ServerStyleSheet } from "styled-components";
93
-
94
- import App from "@/App";
95
- import Metadata from "@/components/Metadata";
96
-
97
- export default function setup(url: string, props: any) {
98
- const pathname = new URL(url).pathname;
99
-
100
- const helmetContext: HelmetDataContext = {};
101
- const sheet = new ServerStyleSheet();
102
- const queryClient = new QueryClient();
103
-
104
- const { query_data = [] } = props;
105
- query_data.forEach(({ key, data }) => queryClient.setQueryData(key, data));
106
- const state = dehydrate(queryClient);
107
-
108
- const app = sheet.collectStyles(
109
- <HelmetProvider context={helmetContext}>
110
- <Metadata url={url} />
111
- <QueryClientProvider client={queryClient}>
112
- <StaticRouter location={pathname}>
113
- <App />
114
- </StaticRouter>
115
- </QueryClientProvider>
116
- <template id="state" data-state={JSON.stringify(state)} />
117
- </HelmetProvider>,
118
- );
119
-
120
- return { app, helmetContext, sheet, queryClient };
121
- }
122
- ```
123
-
124
- 3. Update your `application.tsx` to hydrate on the client:
125
-
126
- ```tsx
127
- import { HelmetProvider } from "@dr.pogodin/react-helmet";
128
- import { hydrateRoot } from "react-dom/client";
129
- import { BrowserRouter } from "react-router";
130
- import { Hydrate, QueryClient, QueryClientProvider } from "react-query";
131
- import App from "@/App";
132
- import Metadata from "@/components/Metadata";
133
-
134
- const queryClient = new QueryClient();
135
-
136
- const stateEl = document.getElementById("state");
137
- const state = JSON.parse(stateEl?.dataset.state ?? "{}");
138
- stateEl?.remove();
139
-
140
- hydrateRoot(
141
- document.getElementById("root")!,
142
- <HelmetProvider>
143
- <Metadata url={window.location.href} />
144
- <QueryClientProvider client={queryClient}>
145
- <Hydrate state={state}>
146
- <BrowserRouter>
147
- <App />
148
- </BrowserRouter>
149
- </Hydrate>
150
- </QueryClientProvider>
151
- </HelmetProvider>,
152
- );
153
- ```
154
-
155
- 4. Create an SSR entry point at `app/frontend/ssr/ssr.ts`:
156
-
157
- ```ts
158
- import { head, transform } from "@/ssr/utils";
159
- import { renderToString } from "react-dom/server.node";
160
- import { createServer } from "universal-renderer";
161
-
162
- const app = await createServer({
163
- setup: (await import("@/ssr/setup")).default,
164
-
165
- render: ({ app, helmet, sheet }) => {
166
- const root = renderToString(app);
167
- const styles = sheet.getStyleTags();
168
- return {
169
- head: head({ helmet }),
170
- body: `${root}\n${styles}`,
171
- };
172
- },
173
-
174
- cleanup: ({ sheet, queryClient }) => {
175
- sheet?.seal();
176
- queryClient?.clear();
177
- },
178
- });
179
-
180
- app.listen(3001);
181
- ```
182
-
183
- 5. Build the SSR bundle:
184
-
185
- ```bash
186
- $ bin/vite build --ssr
187
- ```
188
-
189
- 6. Start your servers:
190
-
191
- ```Procfile
192
- web: bin/rails s
193
- ssr: bin/vite ssr
194
- ```
136
+ The gem never reads ENV itself; bind whatever keys you like in the initializer.
137
+ The suggested prefix is `UNIVERSAL_RENDERER_*`.
195
138
 
196
- ## Development
139
+ | Option | Default | Notes |
140
+ | -------------- | ---------------- | ---------------------------------------------------------------- |
141
+ | `url` | `nil` | Blank disables SSR entirely. |
142
+ | `timeout` | `3` | Open and read timeout, seconds. |
143
+ | `render_path` | `nil` | `nil` uses the path already in `url`. |
144
+ | `stream_path` | `"/stream"` | Must match the Node side. |
145
+ | `sanitize` | `true` | See below. |
146
+ | `scrubber` | `Scrubber.new` | Any `Loofah::Scrubber`. |
147
+ | `auto_include` | `true` | `false` to include `Renderable` per controller instead. |
148
+ | `on_error` | `nil` | `->(error, context) { ... }` |
149
+
150
+ ### Sanitization
151
+
152
+ `ssr_head` and `ssr_body` run the render through Loofah by default.
153
+
154
+ Be clear about what that buys you. The bundled scrubber is a **blocklist**, and
155
+ a blocklist over the whole HTML grammar cannot be a boundary against
156
+ attacker-controlled markup: the sanitizer and the browser have to agree on how
157
+ the document parses, and elements that switch parsing context are how they stop
158
+ agreeing. The scrubber removes the ones that are known to do this (`noscript`,
159
+ the MathML integration points) and pins them with tests, but treat it as defense
160
+ in depth over HTML your own renderer produced — **escape untrusted data inside
161
+ the render**, which React already does unless you reach for
162
+ `dangerouslySetInnerHTML`.
163
+
164
+ It also parses and rewrites the whole document on the Rails side of every
165
+ request, which eats into the latency SSR is meant to buy. `c.sanitize = false`
166
+ is a reasonable trade once you are confident about what the renderer emits. It
167
+ defaults to on because the cost is bounded and the mistake it catches is not.
168
+
169
+ ### Observability
170
+
171
+ Every failed render is a silent fallback, so without a signal you cannot tell a
172
+ healthy renderer from one that has been down for a week:
173
+
174
+ ```ruby
175
+ ActiveSupport::Notifications.subscribe("render.universal_renderer") do |event|
176
+ StatsD.timing("ssr.duration", event.duration,
177
+ tags: ["outcome:#{event.payload[:outcome]}"])
178
+ end
179
+
180
+ c.on_error = ->(error, context) { Sentry.capture_exception(error, extra: context) }
181
+ ```
182
+
183
+ `outcome` is one of `:ok`, `:not_configured`, `:http_error`, `:timeout`, `:error`.
184
+ The notification fires even when no renderer URL is configured; `on_error` is
185
+ reserved for failures after a configured render is attempted.
186
+
187
+ ## The renderer
188
+
189
+ ### The render config
190
+
191
+ One module holds the whole render (`app/frontend/ssr/config.ts` by convention).
192
+ Both entry points load it.
193
+
194
+ ```tsx
195
+ import { dehydrate } from "@tanstack/react-query";
196
+ import { renderToString } from "react-dom/server";
197
+ import { StaticRouter } from "react-router";
198
+ import { ServerStyleSheet } from "styled-components";
199
+ import type { SsrConfig } from "universal-renderer";
200
+ import { hydrateReactQuery } from "universal-renderer/react-query";
201
+
202
+ import { setBrowserLocation } from "./globals";
203
+ import App from "@/App";
204
+ import { preloadRoute, queryClient } from "@/App";
205
+
206
+ export default {
207
+ setup: async (url, props) => {
208
+ const { pathname, search } = new URL(url);
209
+ setBrowserLocation(url);
210
+
211
+ queryClient.clear();
212
+ hydrateReactQuery(props, queryClient);
213
+ await preloadRoute(pathname);
214
+
215
+ const sheet = new ServerStyleSheet();
216
+ const app = sheet.collectStyles(
217
+ <StaticRouter location={`${pathname}${search}`}>
218
+ <App />
219
+ </StaticRouter>,
220
+ );
221
+
222
+ return { app, sheet, props, state: dehydrate(queryClient) };
223
+ },
224
+
225
+ prepare: (context) => {
226
+ context.previousFlags = { ...FEATURE_FLAGS };
227
+ Object.assign(FEATURE_FLAGS, context.props.feature_flags);
228
+ },
229
+
230
+ render: ({ app, sheet, state }) => ({
231
+ body: renderToString(app),
232
+ head: sheet.getStyleTags(),
233
+ payload: { state },
234
+ }),
235
+
236
+ cleanup: ({ sheet, previousFlags }) => {
237
+ Object.assign(FEATURE_FLAGS, previousFlags);
238
+ sheet.seal();
239
+ queryClient.clear();
240
+ },
241
+ } satisfies SsrConfig<any>;
242
+ ```
243
+
244
+ The four hooks are not arbitrary:
245
+
246
+ - **`setup`** is async and must not touch module-level state. It awaits things —
247
+ a lazy route chunk, a fetch — and a mutation made before an await point stays
248
+ visible for as long as the await lasts.
249
+ - **`prepare`** is sync and runs immediately before the render, with no await in
250
+ between. This is where shared singletons get mutated.
251
+ - **`render`** produces the HTML and the hydration payload.
252
+ - **`cleanup`** always runs, and runs before the next render starts. Undo
253
+ `prepare` here.
254
+
255
+ ### Concurrency
256
+
257
+ Renders are **serialized by default**. An app retrofitted with SSR keeps
258
+ request-scoped state in module-level singletons — a store, a query client, a
259
+ mutable feature-flag object, a CSS-in-JS registry — and two renders interleaving
260
+ through those is not a slow page, it is one visitor's data in another visitor's
261
+ HTML. Scale out with more renderer processes; the Puma plugin starts one per
262
+ web server, so SSR capacity tracks your web dyno count.
263
+
264
+ Raise `concurrency` (or pass `"unbounded"`) only once you have verified the render
265
+ touches no shared mutable state.
266
+
267
+ The renderer admits at most ten waiting requests per concurrency slot by
268
+ default. It returns `503` when that queue is full and removes requests that
269
+ disconnect while waiting, so a Rails timeout cannot leave stale renders ahead
270
+ of live traffic. Configure `queueLimit` only if the default does not fit your
271
+ traffic and render latency.
272
+
273
+ ### Render timeout and health
274
+
275
+ Serializing renders has a cost worth naming: a slot is never taken back from a
276
+ running render — it is still touching module state, and handing that slot on is
277
+ the interleaving `concurrency` exists to prevent — so **one render that never
278
+ settles ends the renderer**. At `concurrency: 1` the queue fills, everything
279
+ after it gets `503`, and Rails falls back to client rendering indefinitely.
280
+
281
+ Two separate settings bound it, because "over budget" and "never finishing" are
282
+ different questions:
197
283
 
198
- To contribute to this project:
284
+ - `renderTimeout` (default `2500`ms, `false` to disable) answers the caller with
285
+ `504` instead of hanging. For a streaming render it caps time to first byte,
286
+ not the whole response.
287
+ - `stallAfterMs` (default `30000`ms, `false` to disable) is how long one render
288
+ may hold its slot before `GET /health` returns `503` with
289
+ `{ status: "STALLED", renders: {...} }`.
199
290
 
200
- 1. Clone the repository:
291
+ Do not collapse these into one value. A streaming response holds its slot until
292
+ its last chunk, so a stall threshold near `renderTimeout` reports perfectly
293
+ healthy streams as stalled and invites a supervisor to restart the renderer
294
+ mid-response. Raise `stallAfterMs` above your slowest legitimate stream; the 30s
295
+ default is also roughly where Heroku's router and most ALB defaults have already
296
+ abandoned the request.
201
297
 
202
- ```bash
203
- git clone https://github.com/thaske/universal_renderer.git
204
- cd universal_renderer
205
- ```
298
+ Nothing inside the process can clear a stuck render, so the health signal is the
299
+ point: the Puma plugin polls it and restarts the renderer without touching the
300
+ app server.
206
301
 
207
- 2. Initialize and update submodules:
302
+ Development sets both to `false` — a breakpoint in the render outlasts any
303
+ production budget, and a `504` or a restart there is noise.
208
304
 
209
- ```bash
210
- git submodule update --init --recursive
211
- ```
305
+ **Keep `c.timeout` above `renderTimeout`.** The defaults are 3s and 2.5s, so
306
+ the renderer gives up before Rails falls back. Disconnected requests are dropped
307
+ from the queue, but a render already running cannot be taken back; preserve that
308
+ ordering when tuning either timeout.
212
309
 
213
- 3. Install dependencies:
214
- ```bash
215
- bundle install
216
- ```
310
+ ### Entry points
217
311
 
218
- ## Contributing
312
+ Production runs the prebuilt bundle:
219
313
 
220
- Contributions are welcome! Please follow the coding guidelines in the project documentation.
314
+ ```ts
315
+ // app/frontend/ssr/server.ts
316
+ import "./globals";
317
+
318
+ const { default: config } = await import("./config");
319
+ const { startServer } = await import("universal-renderer");
320
+
321
+ await startServer(config);
322
+ ```
323
+
324
+ Development loads the config through Vite, so the app graph gets the same
325
+ transforms the client dev server gives it and edits need no rebuild:
326
+
327
+ ```ts
328
+ // app/frontend/ssr/dev.ts
329
+ import "./globals";
330
+
331
+ const { startDevServer } = await import("universal-renderer/dev");
332
+
333
+ await startDevServer({ entry: "app/frontend/ssr/config.ts" });
334
+ ```
335
+
336
+ These must not be the same file. A Vite dev server transforming modules per render
337
+ is the single largest cost in the SSR path.
338
+
339
+ Note the **dynamic** imports. The app graph touches browser globals while its
340
+ modules evaluate, and static imports are all evaluated before the entry body runs,
341
+ so `./globals` would land too late.
342
+
343
+ ### Browser globals
344
+
345
+ `renderToString` does not run effects, so `useEffect` is safe. It does still
346
+ evaluate every module in the graph and every render body, and a client-first app
347
+ reaches for `window`, `document`, `localStorage`, or `navigator` in both — a
348
+ singleton assigning `window.myThing` at module scope, a component reading
349
+ `window.innerWidth` while rendering. None of that survives under Node, and none
350
+ of it is React's problem to solve.
351
+
352
+ The package does not ship a shim for this, deliberately. Which globals a graph
353
+ touches is a property of that graph, not of SSR, so a library version would be
354
+ guesses: too small to boot your app and too large to reason about. The generator
355
+ scaffolds `app/frontend/ssr/globals.ts` in your app instead, as a starting point
356
+ you own, edit, and delete if it turns out you need none of it. It carries the
357
+ reasoning, including the two things that bite:
358
+
359
+ - Defining `window` makes `typeof window === "undefined"` false process-wide.
360
+ That check is how libraries detect a server, so they all take the browser
361
+ path. Prefer fixing the module that reaches for the DOM.
362
+ - Some libraries decide once, at module-evaluation time, whether they are in a
363
+ browser (`typeof window !== "undefined" ? null : {...}`). Imported after your
364
+ globals, such a library loses its server API for good.
365
+
366
+ ### The SSR build
367
+
368
+ ```ts
369
+ // vite.config.ssr.mts
370
+ import react from "@vitejs/plugin-react";
371
+ import { defineSsrConfig } from "universal-renderer/vite";
372
+
373
+ export default defineSsrConfig({
374
+ entry: "app/frontend/ssr/server.ts",
375
+ plugins: [react()],
376
+ });
377
+ ```
378
+
379
+ `defineSsrConfig` exists because a Rails SSR build has six settings that are each
380
+ wrong by default and each fail *silently* — you get a bundle, it just renders the
381
+ wrong thing. Note in particular what is **absent**: `vite-plugin-rails`, which is
382
+ built for the client manifest pipeline and overrides entrypoints and outDir. List
383
+ only the plugins the render itself needs; your client build keeps using
384
+ `vite.config.mts` unchanged. See the function's docs for the others.
385
+
386
+ The bundle lands at `ssr-build/server.mjs`, deliberately outside `public/` — it is
387
+ server code and must not be web-servable. It is self-contained: dependencies are
388
+ bundled (`ssr.noExternal: true`), so it runs from a slug whose `node_modules` was
389
+ pruned after the build, and `process.env.NODE_ENV` is replaced at build time, as
390
+ Vite does for client builds (the `NODE_ENV` the build runs with, or
391
+ `"production"`), so React does not run its development build on a host that never
392
+ sets `NODE_ENV`. If the renderer does start on a development build, `startServer`
393
+ logs a warning saying so.
394
+ Keep client-only packages that cannot be bundled, such as anything with a native
395
+ module, out with `ssr.external`:
396
+
397
+ ```ts
398
+ export default defineSsrConfig({
399
+ entry: "app/frontend/ssr/server.ts",
400
+ plugins: [react()],
401
+ // Lazy, client-only, and its `canvas` dependency is native.
402
+ ssr: { external: ["react-pdf", "pdfjs-dist"] },
403
+ });
404
+ ```
405
+
406
+ ### Running it
407
+
408
+ ```procfile
409
+ # Procfile.dev
410
+ web: bin/rails s
411
+ vite: bin/vite dev
412
+ ssr: bun app/frontend/ssr/dev.ts
413
+ ```
414
+
415
+ In production the renderer runs beside your app server on the same host rather
416
+ than as a separate process type, because PaaS process types get no routable
417
+ address for each other. If the renderer dies, requests fall back to client
418
+ rendering; that is a degraded page, not an outage, so it must not take the app
419
+ server down. Something still has to bring the renderer back.
420
+
421
+ #### With Puma
422
+
423
+ ```ruby
424
+ # config/puma.rb
425
+ if ENV.fetch("RAILS_ENV", "development") == "production"
426
+ plugin :universal_renderer
427
+ universal_renderer port: 3001 # optional, after the plugin line
428
+ end
429
+ ```
430
+
431
+ Your Procfile stays `web: bundle exec puma -C config/puma.rb`. Keep the plugin to
432
+ production: in development, `Procfile.dev` runs the development renderer on the
433
+ same port.
434
+
435
+ Puma runs plugins in its master process, so a clustered Puma gets one renderer
436
+ per server, not one per worker. The plugin:
437
+
438
+ - starts the renderer in its own process group, so a wrapper script cannot leave
439
+ a child holding the port;
440
+ - restarts it when it exits, waiting 1, 2, 4, up to 30 seconds while it keeps
441
+ dying at boot, and 1 second again once it has run for a minute;
442
+ - restarts it when `/health` fails three checks in a row, 10 seconds apart (a
443
+ stalled render, a blocked event loop);
444
+ - stops it with Puma, and replaces it on a hot (`USR2`) or phased (`USR1`)
445
+ restart, so a phased restart also picks up a new bundle;
446
+ - skips it, with a log line, when the bundle has not been built.
447
+
448
+ Each start, exit and restart is logged with a `[universal_renderer]` prefix. Each
449
+ option falls back to an environment variable, then to the default:
450
+
451
+ | Option | Variable | Default | Purpose |
452
+ | --------- | ------------- | ---------------------- | ------------------------------------- |
453
+ | `runtime` | `SSR_RUNTIME` | `bun` | Set to `node` if not Bun. |
454
+ | `bundle` | `SSR_BUNDLE` | `ssr-build/server.mjs` | Built renderer entry. |
455
+ | `port` | `SSR_PORT` | `3001` | Passed to the renderer as `SSR_PORT`. |
456
+
457
+ #### Other app servers
458
+
459
+ Run `bun ssr-build/server.mjs` beside the app server under your own process
460
+ supervisor, and restart it when it exits or `GET /health` stops returning `200`.
461
+
462
+ ### Sorbet
463
+
464
+ The engine includes `Renderable` into `ActionController::Base` through
465
+ `ActiveSupport.on_load`, which happens at runtime and so is invisible to Sorbet.
466
+ Add a shim, or every `render_ssr` / `add_prop` call is an undefined-method error:
467
+
468
+ ```ruby
469
+ # sorbet/rbi/shims/universal_renderer.rbi
470
+ # typed: true
471
+
472
+ class ActionController::Base
473
+ include UniversalRenderer::Renderable
474
+ end
475
+ ```
476
+
477
+ ## Streaming
478
+
479
+ Streaming is opt-in per controller:
480
+
481
+ ```ruby
482
+ enable_ssr streaming: true
483
+ ```
484
+
485
+ The layout emits `<!-- SSR_HEAD -->` / `<!-- SSR_BODY -->` markers (`ssr_head`
486
+ and `ssr_body` do this for you), Rails posts the rendered layout to the SSR
487
+ service as `template`, and the service streams the substituted document back.
488
+ Provide `streamCallbacks` in the render config to enable the endpoint. A failed
489
+ stream falls back to a normal blocking render.
490
+
491
+ ## Development
492
+
493
+ ```bash
494
+ bundle install && bun install
495
+
496
+ bundle exec rspec # gem
497
+ bundle exec rubocop
498
+ cd universal-renderer && bun run test && bunx tsc --noEmit
499
+ ```
221
500
 
222
501
  ## License
223
502
 
224
- Available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
503
+ MIT