Skip to content

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:
    (ssr-handler opts) → (fn [ring-request] ring-response)
    
  • Description: Returns a synchronous Ring handler that renders one re-frame2 SSR request per call. For each request it:
    1. stores the Ring request in the per-frame request slot, where the :rf.server/request cofx reads it;
    2. creates the per-request frame from :frame, draining its :initial-events synchronously;
    3. 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);
    4. 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 into Set-Cookie headers;
    5. destroys the frame in a finally.
  • Options:

    • :frame (required) — the app's frame config, the map make-frame takes 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/managed in tests), the :ssr config map, :url-strategy and every other key — under the handler's own :id (a fresh per-request id) and :platform :server.
      • :id or :platform inside :frame throws :rf.error/ssr-ring-frame-opt-invalid at construction, and so does a :frame that is not a map. So does any of :initial-events, :fx-overrides, :ssr or :url-strategy at the handler's top level: the message names :frame.
      • :url-strategy makes route-link hrefs in the server markup match what the hydrated client produces. A malformed value, an explicit nil included, fails the request with :rf.error/invalid-url-strategy through :on-error. Under re-frame.ssr.ring.node/renderer this 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 :frame because 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/managed request, 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-events at construction.
      • Neither a vector nor a fn, or a fn returning a non-vector: :rf.error/invalid-initial-events per request, answered through :on-error.
      • An event handler, interceptor, coeffect or flow that throws during this drain, or a :rf.cofx value its :schema rejects, aborts frame construction with :rf.error/initial-events-step-failed. The request answers through :on-error; the error projector and :error-view never see it. An effect that throws, or an unregistered event, is projected instead.
    • :root-view (required unless :renderer is 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 Var rf/reg-view defines, 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-view at construction. Any other shape raises :rf.error/invalid-root-view at render time, projected like any render throw to the 5xx error page.
    • :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-db keyword 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-db is {}.
      • A path is a non-empty vector of map keys, e.g. [:articles [:session :csrf]]. When the frame classifies the value it names :sensitive and 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-db ships all of app-db. Use it only when the whole app-db is safe to expose.
      • At construction, an absent or nil value 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-sensitive option.
      • 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 any BigInt, BigInteger, BigDecimal, Ratio or Float, 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 — 1 beside 1.0, 0 beside -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.
    • :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. Default nil, 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-view and :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; default 5000. A resource still unsettled at the deadline settles as a first-load failure, so the request never hangs. The handler passes it to drain-blocking-resources!.
    • :schema-digest — the hydration payload's :rf/schema-digest.
    • :html-shell — (body-html payload-edn opts) → string; default default-html-shell. opts is the handler's options with this request's values in place: :head is the resolved head fragment (or your :head string), :html-attrs and :body-attrs come from the head model, and :payload-tag is the finished hydration payload <script id="__rf_payload">, already escaped. Write :head inside <head>, the attribute bags on <html> and <body>, and splice :payload-tag where the payload goes, as default-html-shell does. 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 keeps text/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. See handler-defaults.
    • :head and :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 with reg-head, and a page with none ships no <title>. A :head string 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-head for the head, and registered views plus the :rf.server/* fx for the body.
    • :script-src (default "/main.js") and :app-element-id (default "app") — the bootstrap script's src and the app element's id, attribute-escaped. :script-src false emits no bootstrap <script src>, for an app that boots from :body-end (for example with a type="module" tag).
      • For all four shell-hook options (:head, :body-end, :script-src, :app-element-id), nil means the default, and any other non-string value except :script-src false throws :rf.error/ssr-trusted-shell-opt-invalid at construction.
    • :lang — the <html lang> value, used when the head model's :html-attrs carries 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-state belongs to re-frame.ssr.ring.node/renderer; a copy at the handler's top level is ignored.

    To ship the per-request frame's error and event records off-box, declare the process default with (rf/configure! {:observability …}) (configure!).

    Use :error-view to customise projected error pages and :on-error for 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 to nil, falls back once to the default template and emits :rf.error/ssr-ring-error-view-failed. A buggy :on-error falls back to default-on-error and emits :rf.error/ssr-ring-on-error-failed. When the server throws explains the model.

    Aspect :error-view :on-error
    Which 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.cofx value).
    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) → hiccup fn. 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-shell and gets no head from reg-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:
    (ssr-middleware opts) → (fn [handler] wrapped-handler)
    
  • Description: Returns Ring middleware that sends requests its :match? predicate accepts to an ssr-handler, and all other requests to the wrapped handler (Mounting in a Ring app).
    • opts are ssr-handler's options, including the required :payload, plus :match?, a (request) → boolean predicate. 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:
    handler-defaults
    ;; => {:html-shell default-html-shell}
    
  • Description: The default ssr-handler options, 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 is default-on-error).
    • :content-type — it has no default; see the ssr-handler option.
  • Example:
    ;; Read the baseline the handler constructor merges under your opts.
    ssr.ring/handler-defaults
    ;; => {:html-shell #object[...]}
    

default-html-shell

  • Kind: function
  • Signature:
    (default-html-shell body-html payload-edn opts) → HTML string
    
  • Description: Wraps the rendered body in a minimal, runnable HTML document. Supply your own with ssr-handler's :html-shell option to change the <head>, scripts or styles.
    • Arguments: body-html is the rendered body (from render-to-string, or a :renderer's :body-html); payload-edn is the hydration payload, already serialised with pr-str; opts are the handler's options, of which :head, :html-attrs, :body-attrs, :body-end, :script-src, :app-element-id, :lang and :payload-tag shape the envelope.
    • The payload <script> arrives as :payload-tag, built by the handler with the fixed id __rf_payload, which the client bootstrap reads with document.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 from payload-edn.
    • The shell emits no <title>; the head fragment passed as :head supplies it.
    • :script-src and :app-element-id are attribute-escaped; :head and :body-end are injected raw.
  • 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:
    (default-on-error request throwable) → ring-response
    
  • Description: The fixed 500 response ssr-handler returns when :on-error is 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 .getMessage can reveal internal topology: JDBC URLs, deploy paths, partial SQL, server class names. For a branded body, supply an :on-error that likewise returns a fixed response and ignores the throwable.
  • Example:
    ;; The response used when :on-error is omitted.
    (ssr.ring/default-on-error request some-throwable)
    ;; => {:status  500
    ;;     :headers {"Content-Type" "text/plain; charset=utf-8"}
    ;;     :body    "Internal error"}
    

Framework integration

Not for application code — used by adapters, tools and the test harness.

  • Kind: function
  • Signature:
    (cookie->set-cookie-header cookie-map) → Set-Cookie header string
    
  • Description: Serialises one structured cookie map, the shape :rf.server/set-cookie takes, to a Set-Cookie header value, per RFC 6265 §4.1. Exposed so tests, other host adapters (Pedestal, http-kit) and one-off callers can serialise a cookie.
    • :name is required. :value is URL-encoded, and serialises as the empty string when absent. Every other key (:max-age, :domain, :path, :expires as an epoch-millis long, :secure, :http-only, :same-site as :strict, :lax or :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 :name that 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-age or :same-site containing 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:
    (ssr.ring/cookie->set-cookie-header
      {:name      "session"
       :value     "abc123"
       :max-age   3600
       :http-only true
       :same-site :lax
       :path      "/"})
    ;; => "session=abc123; Max-Age=3600; Path=/; HttpOnly; SameSite=Lax"