re-frame.ssr.ring¶
Serve server-rendered re-frame2 pages from a Ring-compatible server. ssr-handler returns a Ring handler that renders one request per call. For each request the handler creates a frame, runs your setup events, renders the root view and returns a Ring response map; it never writes to a socket itself.
Ships in the day8/re-frame2-ssr-ring artefact, which depends on day8/re-frame2-ssr. The rendering, head model, hydration, SSR events and :rf.server/* fx this handler drives are documented on re-frame.ssr.
(require '[ring.adapter.jetty :as jetty]
'[re-frame.core :as rf]
'[re-frame.ssr :as ssr]
'[re-frame.ssr.ring :as ssr.ring])
(rf/init! ssr/adapter)
;; Load the app namespaces that register :app/server-init and :app/root.
(def handler
(ssr.ring/ssr-handler
{:frame {:initial-events [[:app/server-init]]} ;; each request frame's config: setup events
:root-view (fn [] ((rf/view :app/root))) ;; rendered once those events settle
:payload [:articles :session-user]})) ;; app-db keys shipped to the client
(jetty/run-jetty handler {:port 3000 :join? false})
Those are the three required options; The simplest server walks through what the handler does with them. The client boot, ssr/hydrate!, is on re-frame.ssr.
Handler constructors¶
ssr-handler¶
- Kind: function
- Signature:
- Description: Returns a synchronous Ring handler that renders one re-frame2 SSR request per call. For each request it:
- stores the Ring request in the per-frame request slot, where the
:rf.server/requestcofx reads it; - creates the per-request frame from
:frame, draining its:initial-eventssynchronously; - reads the resolved response accumulator: if it holds a
:redirect, returns the redirect; if an error was projected to a 5xx, returns the error page (:error-view); - otherwise waits for the route's blocking resources (up to 5 seconds,
drain-blocking-resources!), renders:root-view, resolves the head, builds the hydration payload, wraps them in the HTML shell, and turns structured cookies intoSet-Cookieheaders; - destroys the frame in a
finally.
- stores the Ring request in the per-frame request slot, where the
-
Options:
:frame(required) — the app's frame config, the mapmake-frametakes and the browser boot mounts with, so one var serves both halves. Each request frame is made from it whole —:fx-overrides(e.g. to stub:rf.http/managedin tests), the:ssrconfig map,:url-strategyand every other key — under the handler's own:id(a fresh per-request id) and:platform :server.:idor:platforminside:framethrows:rf.error/ssr-ring-frame-opt-invalidat construction, and so does a:framethat is not a map. So does any of:initial-events,:fx-overrides,:ssror:url-strategyat the handler's top level: the message names:frame.:url-strategymakesroute-linkhrefs in the server markup match what the hydrated client produces. A malformed value, an explicitnilincluded, fails the request with:rf.error/invalid-url-strategythrough:on-error. Underre-frame.ssr.ring.node/rendererthis frame does not render the body, and only projected state crosses to Node; pass the same config var as the render module's:frame-opts, or Node-rendered hrefs drop the base path (Render on Node).
:initial-events(required, inside:frame) — the events dispatched, synchronously and in order, into the per-request frame when it is created, after the handler fills the request slot. It lives inside:framebecause it is frame config: the browser boot runs the same events. A vector of events, or(fn [request] → initial-events-vector)to derive them from the Ring request. The fn form is the replay-safe way to put a request-derived fact into a boot event's payload, e.g.(fn [req] [[:auth/server-init {:user (extract-user req)}]]). For non-durable request reads inside a handler, declare:rf.cofx/requires [:rf.server/request]on the registration instead.- The drain covers synchronous work only. A fetch these events start, such as an
:rf.http/managedrequest, is usually still in flight when rendering begins, and the page renders without its data. Data the first render needs belongs in a resource the route declares:blocking? true(Data the first render needs), which the handler waits for. - Omitted from
:frame: throws:rf.error/ssr-ring-missing-initial-eventsat construction. - Neither a vector nor a fn, or a fn returning a non-vector:
:rf.error/invalid-initial-eventsper request, answered through:on-error. - An event handler, interceptor, coeffect or flow that throws during this drain, or a
:rf.cofxvalue its:schemarejects, aborts frame construction with:rf.error/initial-events-step-failed. The request answers through:on-error; the error projector and:error-viewnever see it. An effect that throws, or an unregistered event, is projected instead.
- The drain covers synchronous work only. A fetch these events start, such as an
:root-view(required unless:rendereris given) — what to render against the per-request frame once the drain settles: a hiccup vector such as[(rf/view :app/root)], or a 0-arity fn returning hiccup. The head must be callable: the Varrf/reg-viewdefines, or(rf/view :id). A keyword head is an HTML element on every host, so[:app/root]renders an empty<root>element.- Both forms emit identical HTML:
[(rf/view :app/root)]and(fn [] ((rf/view :app/root)))are interchangeable. A hydration mismatch is reported by the client root that adopts the page, whichever form the server used (When the renders disagree). - Omitted without
:renderer: throws:rf.error/ssr-ring-missing-root-viewat construction. Any other shape raises:rf.error/invalid-root-viewat render time, projected like any render throw to the 5xx error page.
- Both forms emit identical HTML:
:payload(required) — the hydration-payload policy (:payload— the fail-closed allowlist). It fails closed, in one of two shapes:- A sequential of top-level
app-dbkeyword keys and paths is an allowlist. Use a vector; lists and lazy sequences are accepted too. Sets are not allowlists. Only the listed keys, and the values the paths reach, ship in:rf/app-db; everything else is dropped, including keys added later. An empty allowlist,[], ships nothing::rf/app-dbis{}. - A path is a non-empty vector of map keys, e.g.
[:articles [:session :csrf]]. When the frame classifies the value it names:sensitiveand that value is a leaf, the path ships it raw; every other classified value ships as:rf/redacted, including the classified values inside a key or map you name (Classified values inside the allowlist). :rf.ssr.payload/whole-app-dbships all ofapp-db. Use it only when the wholeapp-dbis safe to expose.- At construction, an absent or
nilvalue or an unsupported non-keyword shape (such as a set) throws:rf.error/ssr-missing-payload-policy, an unrecognised keyword throws:rf.error/ssr-unknown-payload-policy, and an allowlist with an entry that is neither a keyword nor a path throws:rf.error/ssr-malformed-payload-allowlist, as does a:payload-include-sensitiveoption. - The payload is written as EDN and read back by the browser, so a number the browser would read back as a different value fails the request with
:rf.error/ssr-hydration-payload-invalid, naming the path and class: an integer outside −(2^53 − 1) through 2^53 − 1, or anyBigInt,BigInteger,BigDecimal,RatioorFloat, map keys and set members included. Narrow the value (an id to a string, money to integer cents) or leave its key off the allowlist. A map or set holding two numbers the browser reads as one value —1beside1.0,0beside-0.0, at any depth — fails the same way, because the browser's reader rejects the duplicate; the error names the path, the colliding values and the value they become. Give the numbers one type or make them strings, or leave its key off the allowlist. A symbol whose text contains</or<!fails with:rf.error/ssr-edn-script-breakout. Either failure is projected like a render throw, so the request answers the error page.
- A sequential of top-level
:client-frame-id— a stable frame id written as the payload's:rf/frame-id, for deployments where server and client agree on one ahead of time. Defaultnil, which omits:rf/frame-id. Never use a per-request gensym: the client rejects a present and different id with:rf.error/hydration-frame-id-mismatch.:error-viewand:on-error— the two failure handlers, described in the table below.:ssr-blocking-timeout-ms— how long the request waits for the route's blocking resources to settle before it renders; default5000. A resource still unsettled at the deadline settles as a first-load failure, so the request never hangs. The handler passes it todrain-blocking-resources!.:schema-digest— the hydration payload's:rf/schema-digest.:html-shell—(body-html payload-edn opts) → string; defaultdefault-html-shell.optsis the handler's options with this request's values in place::headis the resolved head fragment (or your:headstring),:html-attrsand:body-attrscome from the head model, and:payload-tagis the finished hydration payload<script id="__rf_payload">, already escaped. Write:headinside<head>, the attribute bags on<html>and<body>, and splice:payload-tagwhere the payload goes, asdefault-html-shelldoes. The page shell shows the common changes.:content-type— replaces the response Content-Type when supplied. It has no default: omit it (the normal case) and the response keepstext/html; charset=utf-8, from the runtime's default or from the app's own:rf.server/set-header "content-type". It applies to successful pages only; a projected error page keeps the accumulated Content-Type. Seehandler-defaults.:headand:body-end— raw HTML strings injected into the envelope verbatim, without escaping. A page normally gets its<title>from the active route's:head, declared withreg-head, and a page with none ships no<title>. A:headstring replaces that resolved head, default viewport meta included, for a static app without routing.- Never build them from untrusted input (a CMS field, a tenant-admin form, a query-string parameter): they are injected unescaped, so that is a script-injection hole. For such content use
reg-headfor the head, and registered views plus the:rf.server/*fx for the body.
- Never build them from untrusted input (a CMS field, a tenant-admin form, a query-string parameter): they are injected unescaped, so that is a script-injection hole. For such content use
:script-src(default"/main.js") and:app-element-id(default"app") — the bootstrap script'ssrcand the app element'sid, attribute-escaped.:script-src falseemits no bootstrap<script src>, for an app that boots from:body-end(for example with atype="module"tag).- For all four shell-hook options (
:head,:body-end,:script-src,:app-element-id),nilmeans the default, and any other non-string value except:script-src falsethrows:rf.error/ssr-trusted-shell-opt-invalidat construction.
- For all four shell-hook options (
:lang— the<html lang>value, used when the head model's:html-attrscarries no:lang; default"en".:renderer— a fn that renders the body in place of the local renderer:(fn [{:keys [frame-id request opts]}] → {:body-html <string>}). It is called once per request inside the request frame's scope, after the boot-event drain and the blocking-resource settle, and before head resolution and the payload build use its result. It receives the post-drain frame id, the Ring request and the handler opts, never a hiccup value, and returns only the body markup.- The renderer owns
:body-html; the handler does not rewrite custom body HTML. - A throw is projected like any render-time throw.
- Omitted, the handler renders locally: resolve
:root-view, then render it. - re-frame2 ships one other renderer,
re-frame.ssr.ring.node/renderer, which renders on a Node sidecar (renderer). :render-statebelongs tore-frame.ssr.ring.node/renderer; a copy at the handler's top level is ignored.
- The renderer owns
To ship the per-request frame's error and event records off-box, declare the process default with
(rf/configure! {:observability …})(configure!).Use
:error-viewto customise projected error pages and:on-errorfor failures outside projection. Both have usable defaults. A failure the error projector catches is classified by its projected status. A projected 4xx (a routing miss, bad client input) keeps the app's own not-found or bad-request body and hydration payload and does not call:error-view; a projected 5xx ships the error page, with the projected status and no hydration payload. A root view or shell that throws while rendering always ships the error page, whatever status the projector chose, because there is no body to keep. A buggy:error-view, whether it throws or depends on a subscription that recovers tonil, falls back once to the default template and emits:rf.error/ssr-ring-error-view-failed. A buggy:on-errorfalls back todefault-on-errorand emits:rf.error/ssr-ring-on-error-failed. When the server throws explains the model.Aspect :error-view:on-errorWhich failure? A projected 5xx the error projector catches: an effect that throws or an unregistered event during the drain, a subscription or view that throws while rendering, or an unrenderable root or shell. A transport / Ring-layer failure the projector cannot see: a throw while setting up the per-request frame, a throw while materialising headers or cookies, or a failed initial event (an event handler, interceptor, coeffect or flow that throws, or a rejected :rf.cofxvalue).What does it produce? The error-page body (hiccup). Either a registered-view keyword, resolved as [(rf/view error-view) public-error](an unregistered keyword falls back to the default template), or a(public-error) → hiccupfn. It renders through the standard SSR emitter, with no app body or hydration payload beside it. Its HTML is the whole response body, prefixed with<!DOCTYPE html>as the default template is: it is not wrapped in:html-shelland gets no head fromreg-head, so return a complete document,[:html [:head …] [:body …]].A raw Ring response map {:status … :headers … :body …}, returned to the server as is.What is its input? Only the public-error map, sanitised by the projector and safe to render; never the request, the throwable or the frame. The raw (request throwable), including the unsanitised throwable. The default never reads it.Default when omitted? A minimal default error template. Omitting it does not keep the root body. A minimal fixed 500(default-on-error) that leaks no internal detail. -
Example:
;; The required three, plus the options most deployments add. (def handler (ssr.ring/ssr-handler {:frame {:initial-events (fn [req] [[:auth/server-init {:user (extract-user req)}]]) :ssr {:public-error-id :app/public-error}} :root-view (fn [] ((rf/view :app/root))) :payload [:articles :session-user] :error-view :app/error-page ;; registered view; receives the public error :script-src "/js/main.js"}))
ssr-middleware¶
- Kind: function
- Signature:
- Description: Returns Ring middleware that sends requests its
:match?predicate accepts to anssr-handler, and all other requests to the wrapped handler (Mounting in a Ring app).optsaressr-handler's options, including the required:payload, plus:match?, a(request) → booleanpredicate. Truthy renders with SSR; falsy calls the wrapped handler.:match?defaults to matching every GET request.
- Example:
;; ssr-middleware is curried: (ssr-middleware opts) returns a Ring ;; middleware (handler) → wrapped-handler. Apply it to the fallback ;; handler, then compose normally. (def app (-> default-handler ((ssr.ring/ssr-middleware {:frame {:initial-events [[:app/server-init]]} :root-view (fn [] ((rf/view :app/root))) :payload [:articles :session-user] :match? (fn [req] (= :get (:request-method req)))})) wrap-static-assets))
Rendering on a Node sidecar¶
re-frame.ssr.ring.node/renderer is the one other :renderer re-frame2 ships, for a view layer whose components are JavaScript, such as a Fresco root: it sends the settled request frame's state to a Node render sidecar and takes back the body markup, while the head, payload, shell, status, headers and error projection stay on the JVM. Its options, errors and defaults are on re-frame.ssr.ring.node.
Defaults and overrides¶
handler-defaults¶
- Kind: var (map)
- Signature:
- Description: The default
ssr-handleroptions, merged under the caller's options at construction; caller values win. A data var, exposed so callers can read or extend the baseline. Two options are not in it::on-error— resolved separately (the default isdefault-on-error).:content-type— it has no default; see thessr-handleroption.
- Example:
default-html-shell¶
- Kind: function
- Signature:
- Description: Wraps the rendered body in a minimal, runnable HTML document. Supply your own with
ssr-handler's:html-shelloption to change the<head>, scripts or styles.- Arguments:
body-htmlis the rendered body (fromrender-to-string, or a:renderer's:body-html);payload-ednis the hydration payload, already serialised withpr-str;optsare the handler's options, of which:head,:html-attrs,:body-attrs,:body-end,:script-src,:app-element-id,:langand:payload-tagshape the envelope. - The payload
<script>arrives as:payload-tag, built by the handler with the fixed id__rf_payload, which the client bootstrap reads withdocument.getElementById("__rf_payload"). Its EDN body is escaped so a payload containing</script>cannot close the element. The default shell splices it, and a custom shell does the same; called without:payload-tag, the default shell builds the identical tag frompayload-edn. - The shell emits no
<title>; the head fragment passed as:headsupplies it. :script-srcand:app-element-idare attribute-escaped;:headand:body-endare injected raw.
- Arguments:
- Example:
;; The default envelope, invoked directly (the handler does this for you). (ssr.ring/default-html-shell "<div>rendered body</div>" "{:rf/version 1 :rf/app-db {}}" ;; pr-str'd hydration payload {:head "<title>MyApp</title>" :script-src "/js/main.js"}) ;; => "<!DOCTYPE html><html lang=\"en\"><head>…</head><body>…</body></html>"
default-on-error¶
- Kind: function
- Signature:
- Description: The fixed
500responsessr-handlerreturns when:on-erroris omitted.- It covers failures outside projection: per-request setup (including failed initial-event steps), and header or cookie materialisation. A root or shell render failure goes through the projector and
:error-view. - It ignores the throwable and returns a generic plain-text body, because
.getMessagecan reveal internal topology: JDBC URLs, deploy paths, partial SQL, server class names. For a branded body, supply an:on-errorthat likewise returns a fixed response and ignores the throwable.
- It covers failures outside projection: per-request setup (including failed initial-event steps), and header or cookie materialisation. A root or shell render failure goes through the projector and
- Example:
Framework integration¶
Not for application code — used by adapters, tools and the test harness.
cookie->set-cookie-header¶
- Kind: function
- Signature:
- Description: Serialises one structured cookie map, the shape
:rf.server/set-cookietakes, to aSet-Cookieheader value, per RFC 6265 §4.1. Exposed so tests, other host adapters (Pedestal, http-kit) and one-off callers can serialise a cookie.:nameis required.:valueis URL-encoded, and serialises as the empty string when absent. Every other key (:max-age,:domain,:path,:expiresas an epoch-millis long,:secure,:http-only,:same-siteas:strict,:laxor:none, or a string written verbatim) becomes an attribute after a semicolon.
- Errors:
:rf.error/cookie-missing-name— no:name.:rf.error/cookie-invalid-name— a:namethat is not a string, keyword or symbol, or does not match the RFC 6265 §4.1.1 token grammar.:rf.error/cookie-invalid-attribute—:domain,:path,:max-ageor:same-sitecontaining CR, LF, NUL or a raw;. These are checked before concatenation, which prevents header splitting and attribute injection.:rf.error/cookie-invalid-expires— a non-integer:expires.
- Example: