Server rendering
Render on the server, transfer state explicitly, and hydrate without re-rendering.
Server rendering sends real HTML on the first load, so content shows before any JavaScript runs. Hydration then makes that HTML interactive in the browser, without rendering it again.
How it fits together
Three modules line up with the render flow:
- SSR renders nodes to HTML.
- SSRState serializes state on the server and restores it in the browser.
- Hydration attaches reactivity and event handlers to the existing DOM.
The browser never re-renders what the server already produced. Hydration walks the server HTML, reconnects the reactive parts, and carries on from there.
Render on the server
Use SSR.renderToString for a fragment, and SSR.renderToStringWithRoot when you want it wrapped in a root element to hydrate later.
1open Xote23module App = {4 @xote.component5 let make = () =>6 <div>7 <h1> {"Hello from the server"} </h1>8 </div>9}1011let app = () => <App />1213let html = SSR.renderToStringWithRoot(app, ~rootId="root")
Render a full document
Use SSR.renderDocument when the server sends the whole HTML page. It renders your app into <div id="root">, and adds the hydration script and any styles and scripts you list.
1let html = SSR.renderDocument(2 ~head="<title>Xote App</title>",3 ~styles=["/app.css"],4 ~scripts=["/client.js"],5 ~stateScript=SSRState.generateScript(),6 app,7)
Check where code runs
Use SSRContext when code must behave differently on the server and in the browser. SSRContext.isServer and SSRContext.isClient are plain booleans; SSRContext.match picks a branch:
1let greeting = SSRContext.match(2 ~server=() => "Rendered on the server",3 ~client=() => "Rendered in the browser",4)
Transfer state to the browser
If the server and the browser must start from the same state, declare or register the signals with SSRState. On the server they're recorded for the state script; in the browser they're restored from it.
Create synced state
SSRState.signal creates a signal and syncs it in one call:
1let count = SSRState.signal("count", 0, SSRState.Codec.int)2let name = SSRState.signal("name", "Ada", SSRState.Codec.string)
Sync an existing signal
SSRState.sync registers a signal on the server and restores it in the browser:
1let draft = Signal.make("")2SSRState.sync("draft", draft, SSRState.Codec.string)
Important: On the server,
sync(andSSRState.signal) records the signal's value when you call it, not when the state script is generated. A signal set aftersyncis sent with its old value. Load the data first, then callsync. Likewise,generateScriptonly includes what was registered before it runs, and an argument like~stateScript=SSRState.generateScript()runs beforerenderDocumentrenders.
Codecs
Codecs turn values into JSON and back. Use the built-in ones for primitives and common containers, or write your own with SSRState.Codec.make.
1SSRState.Codec.int2SSRState.Codec.float3SSRState.Codec.string4SSRState.Codec.bool5SSRState.Codec.array(SSRState.Codec.string)6SSRState.Codec.option(SSRState.Codec.int)7SSRState.Codec.tuple2(SSRState.Codec.int, SSRState.Codec.string)8SSRState.Codec.dict(SSRState.Codec.int)
On a long-lived server that renders more than one request, call SSRState.clear() before each render so one request's state doesn't leak into the next.
Hydrate in the browser
Hydration connects the browser runtime to the server-rendered DOM without replacing it.
1Hydration.hydrateById(app, "root", ~options={2 onHydrated: () => Console.log("hydrated"),3})
Example: shared counter
A typical setup shares one component between the server and the browser.
Shared component
1open Xote23let count = SSRState.signal("count", 0, SSRState.Codec.int)45module App = {6 @xote.component7 let make = () =>8 <div>9 <h1> {"Count: "} {Signal.get(count)} </h1>10 <button onClick={_ => Signal.update(count, n => n + 1)}> {"Increment"} </button>11 </div>12}1314let app = () => <App />
Server entry
1Router.initSSR(~pathname="/", ())23let html = SSR.renderDocument(4 ~scripts=["/client.js"],5 ~stateScript=SSRState.generateScript(),6 app,7)
Browser entry
1Router.init()2Hydration.hydrateById(app, "root")
Hydration markers
During server rendering Xote puts HTML comments around reactive parts. While hydrating, the browser uses those markers to find reactive text, fragments, keyed lists and lazy components.
Tips
- Render the same component tree on the server and in the browser, so hydration can attach cleanly.
- Initialize the router for each side:
initSSRon the server,initin the browser. See Routing. - Clear
SSRStatebetween server renders, especially in long-lived processes. - Pick codecs on purpose: they're the contract between what the server sends and what the browser restores.
- For hosting a server-rendered or pre-rendered site, see Deploying.
Summary
Server rendering turns a component into an HTML string (SSR.renderToString, SSR.renderToStringWithRoot, SSR.renderDocument); hydration (Hydration.hydrate, Hydration.hydrateById) attaches event listeners and reactive leaves to that HTML in the browser instead of re-creating it. SSRState carries signal values from the server to the client, and SSRContext tells shared code where it runs. The rule that matters most: the client MUST build the same tree, from the same state, as the server; any difference is kept silently as stale server markup or replaced, and nothing throws.
Availability
| Item | Value |
|---|---|
| Modules | SSR, Hydration, SSRState, SSRContext |
| Import / entry | xote (with -open Xote), or xote/ssr, xote/hydration, xote/ssr-state, xote/ssr-context |
| First stable version | 4.14.0 (server rendering with hydration); SSRState.signal / SSRState.sync are the only names since 7.0.0 (SSRState.make and SSRState.syncSignal were removed) |
| Status | stable since 7.1.0 |
| PPX required | No |
Rules
SSR.renderToString(component)callscomponent()and serializes the node tree synchronously. Signals are read with their current value (untracked). The output contains hydration markers (rule 14).- During a server render,
View.onMountcallbacks and element refs never run,Resource.makestarts no fetch, andView.Suspenserenders its fallback. Effect.rundoes run during a server render: an effect created in a component body executes its function once, synchronously, on the server. Browser-only code inside an effect MUST be guarded (SSRContext.isClient) or moved toView.onMount. (TheSSRinterface comment saying effects do not run is wrong; verified against the implementation.)SSR.renderToStringWithRoot(component, ~rootId="root")wraps the output in<!--xote-root:ID-->…<!--/xote-root-->. It does not create an element; put the output inside an element with that id yourself.SSR.renderDocument(~head=?, ~bodyAttrs=?, ~scripts=?, ~styles=?, ~stateScript=?, ~nonce=?, component)returns a full<!DOCTYPE html>document:stylesbecome<link rel="stylesheet">,headandbodyAttrsare inserted raw (not escaped), the app goes into<div id="root">, followed bystateScript, awindow.__XOTE_HYDRATED__=falsescript, and<script type="module">tags forscripts.nonceis added to the generated scripts.- Arguments are evaluated before the call: in
SSR.renderDocument(~stateScript=SSRState.generateScript(), app), the state script is generated beforeapprenders. Anything registered during the render is not in that script. SSRState.register(id, signal, codec)(server only) storescodec.encode(Signal.peek(signal))at call time. Later writes to the signal are not serialized.SSRState.syncandSSRState.signalregister on the server, so the same timing applies.- The
SSRStateregistry is module-level and shared by every request in the process. CallSSRState.clear()at the start of each request. SSRState.generateScript(~nonce=?)emits<script>window.__XOTE_STATE__=...;</script>with the registry as JSON (</script>and<!--escaped).SSRState.restore(id, signal, codec)(client only) sets the signal fromwindow.__XOTE_STATE__[id]if present and decodable; otherwise the signal keeps its value, silently.SSRState.syncrestores on the client;SSRState.signal(id, initial, codec)=Signal.make(initial)+sync.- Restoring MUST happen before hydration. Module-level
SSRState.signalcalls run on import, which is beforeHydration.hydrateByIdin a normal client entry. SSRContext.isServeristypeof document === "undefined", computed once when the module loads;isClientis its inverse.onServer,onClientandmatchbranch on it.Hydration.hydrate(component, container, ~options=?)callscomponent()and walks the container's existing DOM:- elements outside reactive regions are adopted (same DOM nodes); static attributes and static text are left exactly as the server wrote them;
- each reactive text leaf is set to the client's current value, then follows its signal;
- reactive attributes are attached and set from the client's state;
- event listeners are attached;
- keyed lists (
View.Forwith~by) adopt their rows by key; - every reactive region (
if/switchin JSX,View.Show,View.Maybe,View.Value,View.tracked,Router.routes/route,View.Suspense,View.ErrorBoundary) is rendered again on the client: its server DOM is removed and replaced once.
- Hydration markers (HTML comments):
<!--$-->…<!--/$-->reactive text,<!--#-->…<!--/#-->reactive region,<!--kl-->…<!--/kl-->keyed list,<!--k:KEY-->…<!--/k-->keyed row,<!--lc-->…<!--/lc-->component,<!--xote-root:ID-->root. They MUST reach the browser unmodified (no HTML minifier that strips comments). Hydration.hydratesetswindow.__XOTE_HYDRATED__ = true, then callsonHydrated. Refs andView.onMountcallbacks run once the whole tree is hydrated.Hydration.hydrateById(component, id)logs[Xote Hydration] Container element not found: IDwithconsole.errorand does nothing else when the element is missing.renderOptions.renderId,renderOptions.nonce(onrenderToString/renderToStringWithRoot) andhydrateOptions.renderIdare accepted but currently have no effect: markers are not namespaced. Do not rely on them to separate two trees on one page.
API
| Name | Signature | Behaviour |
|---|---|---|
SSR.renderToString | (unit => View.node, ~options: renderOptions=?) => string | HTML with markers; options currently ignored. |
SSR.renderToStringWithRoot | (unit => View.node, ~rootId: string=?, ~options: renderOptions=?) => string | Same, wrapped in root comment markers (default id "root"). |
SSR.renderDocument | (~head: string=?, ~bodyAttrs: string=?, ~scripts: array<string>=?, ~styles: array<string>=?, ~stateScript: string=?, ~nonce: string=?, unit => View.node) => string | Full HTML document, app in <div id="root">. |
SSR.generateHydrationScript | (~nonce: string=?) => string | <script>window.__XOTE_HYDRATED__=false;</script>. |
Hydration.hydrate | (unit => View.node, Dom.element, ~options: hydrateOptions=?) => unit | Attach to existing markup in an element. |
Hydration.hydrateById | (unit => View.node, string, ~options: hydrateOptions=?) => unit | hydrate by element id. |
Hydration.hydrateOptions | {renderId?: string, onHydrated?: unit => unit} | onHydrated runs once after hydration. |
SSRState.register | (string, Signal.t<'a>, Codec.t<'a>) => unit | Server: record the current value. |
SSRState.restore | (string, Signal.t<'a>, Codec.t<'a>) => unit | Client: set from the page's state. |
SSRState.sync | (string, Signal.t<'a>, Codec.t<'a>) => unit | register on the server, restore on the client. |
SSRState.signal | (string, 'a, Codec.t<'a>) => Signal.t<'a> | Signal.make + sync. |
SSRState.clear | unit => unit | Empty the server registry. |
SSRState.generateScript | (~nonce: string=?) => string | <script> with window.__XOTE_STATE__. |
SSRState.getClientState | unit => Dict.t<JSON.t> | Raw state payload (client), {} on the server. |
SSRState.Codec | int, float, string, bool, array, option, tuple2, tuple3, dict, make(~encode, ~decode) | JSON codecs; decode returns option. |
SSRContext.isServer / isClient | bool | Environment, fixed at module load. |
SSRContext.onServer / onClient | (unit => 'a) => option<'a> | Run on one side only. |
SSRContext.match | (~server: unit => 'a, ~client: unit => 'a) => 'a | Pick a branch. |
Patterns
Use for a shared app with state that must survive the trip: declare synced signals at module level, put browser-only reads in View.onMount.
1@val @scope("window") external innerWidth: int = "innerWidth"23let count = SSRState.signal("count", 0, SSRState.Codec.int)45module App = {6 @xote.component7 let make = () => {8 let width = Signal.make(0)9 View.onMount(() => Signal.set(width, innerWidth)) // browser only, after hydration10 <div>11 <h1> {"Count: "} {Signal.get(count)} </h1>12 <p> {"Window width: "} {Signal.get(width)} </p>13 <button onClick={_ => Signal.update(count, n => n + 1)}> {"+"} </button>14 </div>15 }16}1718let app = () => <App />
Use for a request handler that loads data first: clear the registry, seed the router, load, then sync, then render.
1let posts: Signal.t<array<string>> = Signal.make([])23let handleRequest = async (~pathname) => {4 SSRState.clear()5 Router.initSSR(~pathname, ())6 Signal.set(posts, await loadPosts())7 SSRState.sync("posts", posts, SSRState.Codec.array(SSRState.Codec.string)) // after the data is in8 SSR.renderDocument(~scripts=["/client.js"], ~stateScript=SSRState.generateScript(), app)9}
Use for the client entry: restore the same ids, initialize the router, hydrate the element renderDocument created.
1let hydrateClient = () => {2 SSRState.sync("posts", posts, SSRState.Codec.array(SSRState.Codec.string))3 Router.init()4 Hydration.hydrateById(app, "root", ~options={onHydrated: () => Console.log("interactive")})5}
Use for a variant or record: write a codec with SSRState.Codec.make.
1type status = Draft | Published2let statusCodec = SSRState.Codec.make(3 ~encode=status =>4 JSON.String(5 switch status {6 | Draft => "draft"7 | Published => "published"8 },9 ),10 ~decode=json =>11 switch json {12 | JSON.String("draft") => Some(Draft)13 | JSON.String("published") => Some(Published)14 | _ => None15 },16)17let status = SSRState.signal("status", Draft, statusCodec)
Anti-patterns
Touching browser globals in an effect.
1Effect.run(() => {2 Console.log(innerWidth) // window.innerWidth3 None4})
Symptom: ReferenceError: window is not defined (or document is not defined) thrown from the server render. Correct: View.onMount(() => ...), or guard with if SSRContext.isClient. Why: effects run during server renders (rule 3); onMount does not.
Syncing before the data is loaded.
1let posts = SSRState.signal("posts", [], SSRState.Codec.array(SSRState.Codec.string)) // module level2// later, per request:3Signal.set(posts, await loadPosts())
Symptom: the server HTML shows the posts, but the state script carries [], so the client starts from []: reactive text flips to the default on hydration, a keyed list logs Keyed item "KEY" is in the markup but not in the list warnings and stops matching the markup. Correct: call SSRState.sync (or register) after Signal.set, per request, as in the request-handler pattern. Why: rule 7.
Rendering values that differ between server and client.
1<p> {"Generated at " ++ Date.now()->Float.toString} </p>
Symptom: the static text keeps the server's value forever (hydration does not touch static text); event handlers may attach to the wrong elements when structure differs. Correct: render time-dependent or random values from a signal set in View.onMount, or transfer them with SSRState. Why: rule 13 (static text is adopted as-is).
Forgetting SSRState.clear() between requests.
Symptom: one user's data appears in another response's state script. Correct: SSRState.clear() first in every request handler. Why: rule 8.
Stripping comments from the HTML.
Symptom: [Xote Hydration] ... warnings, and reactive text, regions and keyed lists that never update. Correct: disable comment removal in the HTML minifier. Why: rule 14.
Generating the state script after registering during the render, expecting it to be included.
Symptom: values registered by components while rendering are missing from window.__XOTE_STATE__. Correct: register before calling renderDocument, or render with renderToString first and build the document yourself after calling SSRState.generateScript(). Why: rule 6.
Edge cases
SSRContext.isServeris decided at module load. In tests that set up jsdom after importing Xote modules,isServerstaystrue.- Hydration does not reconcile structure. When the client tree differs, elements are matched by position; missing nodes produce
[Xote Hydration] Missing DOM element for Element node/Missing text node for SignalTextwarnings and the rest may bind to the wrong elements. - Keyed lists: a row whose key is in the markup but not in the client's list logs
Keyed item "KEY" is in the markup but not in the list; missing markers logKeyed list markers are missing; the list will not update. - Regions are re-rendered on hydration (rule 13), so focus, selection, scroll positions and loaded images inside them are reset once. Keep forms that users may start typing into before hydration outside reactive regions.
- Router state is global (see
/docs/learn/routing); callRouter.initSSRper request. Codec.intdecodes any JSON number and truncates it;Codec.arrayandCodec.dictfail as a whole if one element fails.renderDocumentemits<html>without alangattribute; add it by building the document yourself if needed.
SSR and hydration
This page is the SSR reference. For per-feature server behaviour see: Resource (no fetch on the server, /docs/learn/async-data), View.ErrorBoundary (renders its fallback into the HTML and re-renders on the client, /docs/learn/lifecycle), View.Portal (renders nothing on the server).
Verify
SSR.renderToString(app)in Node with no DOM must not throw; anywindow/documentreference outsideView.onMountor anSSRContext.isClientguard will.- The HTML must contain the expected markers (
<!--$-->around reactive text,<!--#-->around regions). - Hydration test (jsdom): set
document.body.innerHTMLto the server HTML inside<div id="root">, keep a reference to an element outside any region, callHydration.hydrateById(app, "root"), assert the element is the same object (===) and that clicking a button updates the text. - State test: after
SSRState.clear(),SSRState.sync("x", signal, codec),SSRState.generateScript()must contain"x":with the value present at sync time. - Watch the console for
[Xote Hydration]warnings; any warning means the trees differ.
Related
/docs/learn/routing—Router.initSSRandRouter.init./docs/learn/async-data— resources and Suspense on the server./docs/learn/lifecycle—View.onMount, the place for browser-only code./docs/guides/deploying— prerendering pages to static HTML.