HtmlServer unstable
Server rendering for effect/ui: renders a component tree to HTML that
HtmlHydrate.hydrate hydrates.
renderToHtml builds provided Layers and fetches query data once per key
in a per-request cache. Rendering waits until nothing is in flight or the
budget is spent, then serialises once. No Command runs on the server.
Only query-watch Subscriptions run; other Subscriptions and onMount
work wait for the client.
The result holds the body markup, the state the client adopts, with the
query entries that settled, the root's Model (for the response status),
and the document head as escaped strings. The page puts them together;
serializeState makes the state safe to embed in a <script>.
Set the budget to what your page's data needs, or 0 for no waiting. A budget miss renders the loading Model, with its title, and the client fetches what missed it.
On the client, hydrate the same component with the same props and the
parsed state: HtmlHydrate.hydrate(App, {}, container, state), or
HtmlHydrate.hydrateEffect to wait for root.adopted.
A routed app served through HttpRouter uses layerHttp from
effect/ui/html/HtmlServerHttp instead: it resolves each request's URL,
answers 404s and redirects, and renders the page with
Router.props(routes) as the props.
Example Rendering a page
import { Html, HtmlHead, HtmlServer } from "effect/ui/html"import { Effect, Schema } from "effect"import { Head } from "effect/ui"
const App = Html.component({ name: "App", model: Schema.Struct({}), message: Schema.Never}).make({ init: () => ({}), update: ($) => $.model, head: () => [Head.title("Home"), HtmlHead.lang("en")], view: (h) => h.h1("Home")})
const page = Effect.gen(function*() { const { bodyAttributes, head, html, htmlAttributes, state } = yield* HtmlServer.renderToHtml(App, {}) return `<!doctype html><html ${htmlAttributes}> <head><meta charset="utf-8">${head}</head> <body ${bodyAttributes}> <div id="app">${html}</div> <script type="application/json" id="state">${HtmlServer.serializeState(state)}</script> </body></html>`})Constructors
renderToHtml
unstableRenders a component tree to HTML, with the state the client adopts.
When to use
Use when the render needs services that belong to the request, such as
the current user, or when the server doesn't use HttpRouter. Provide
those services to the returned Effect per request.
Details
It needs the tree's requirements, as BrowserHost.mount does, and runs
in its own Scope. The root must render HTML or be host-neutral. Give a
MessageLog Layer to log the server run; its entries stay on the server.
budget (default 500 ms) is one deadline for the whole render. It limits
waiting on provided Layers and fetches, not the render. A Layer that misses
it, or that Component.provide(..., { server: false }) keeps off the
server, renders its feature children's fallback, and the client builds
that instance fresh. A fetch that misses it isn't shipped, and the client
fetches it after hydration. A child view defect is listed in failures,
renders the child's fallback, and causes the client to rebuild the child.
props may be an Effect, such as Router.props(AppRoute) under
Router.static, run once before init. Its requirements are added to the
render's. The client resolves its own props the same way, from its Router.
static: true is for HTML built at deploy or held in a CDN, where the
data's age is unknown. The client then hydrates every entry stale: it is
invalidated at hydration, and refetched once, unless its query's
staleTime is "Infinity". There is no fetch-free window. A page
prerendered without search params, such as /search, may be served for
/search?q=x, and a 404 prerendered at /404 for any unknown path:
Router.subscription then delivers the Router's route without reporting
RouteMismatch. When options.static is omitted, it reads Static.
The default is false, for per-request HTML whose entries hydrate fresh.
Use distinct key options when rendering the same root component more than
once in one document. Each key sets the root's path to /<name>[<key>]
and is saved in state for HtmlHydrate.hydrate to reuse automatically.
Props are omitted by default. Set includeProps: true to encode the root's
props with its props Schema and read them with HtmlHydrate.decodeProps
on the client. If the Schema contains Schema.Redacted or encoding fails,
props are omitted with a warning once per component. Skip this option when
the client can reconstruct the props, for example with Router.props.
Gotchas
Read data is public: state includes every settled entry, including typed
Failures and entries no view renders, and with includeProps the root's
props.
Route status is the app's: resolve the URL with AppRoute.resolve first,
answer a notFound route with a 404, a redirected one with a
permanent redirect, and one with invalid search keys with a temporary
one, even when it's also redirected. HtmlServerHttp.layerHttp does
this for an app served through HttpRouter.
Signature
declare function renderToHtml<Name extends string, Props, Model, Msg, Events, R, V extends Elements, RP = never>(component: Members<Name, Props, Model, Msg, Events, R, V, any, never> & HtmlRoot<V>, props: PropsInput<Props, never, RP>, options?: { readonly budget?: Input; readonly includeProps?: boolean; readonly key?: string; readonly static?: boolean;}): Effect<Rendered<Model>, never, Exclude<R, Host> | Exclude<RP, Host>>Models
What renderToHtml returns.
Details
html is the body markup for the app's container. state maps each
instance's path to its Schema-encoded Model, plus ~deferred, the
settled query entries under ~query, the reports each owner of shared
state collected under ~reported, ~static for a
static render, ~key when rendered with key, and the root's props under
~props with includeProps;
pass it to HtmlHydrate.hydrate. model is the root's Model
after the server run, for app code that sets the status (a 404 for a
missing record), or undefined if the root failed. failures lists reported
failures, including the root's (see Renderer.ServerFailure). head holds the
<title>, meta, link and JSON-LD tags, and htmlAttributes and
bodyAttributes the attributes for <html ${htmlAttributes}> and
<body ${bodyAttributes}>. All of them are escaped.
Signature
interface Rendered<out Model> { readonly bodyAttributes: string; readonly failures: readonly Array<ServerFailure>; readonly head: string; readonly html: string; readonly htmlAttributes: string; readonly model: Model | undefined; readonly state: State;}References
Utils
Fills an HTML template with a rendered page.
When to use
Use with an index.html that holds the page's static markup and asset
tags. HtmlServerVite.plugin does this with the app's own index.html.
Details
It adds htmlAttributes and bodyAttributes right after the <html>
and <body> tag names, puts head before </head>, replaces the
<!--app-html--> marker with html, and adds the state as
<script type="application/json" id="state"> before </body>.
Gotchas
It throws if the template has no <!--app-html-->, </head> or
</body>. Leave attributes the app sets through its head, such as
lang, out of the template, or the tag gets them twice.
Signature
declare function document(template: string, rendered: Rendered<unknown>): stringExample Filling a template
import { HtmlServer } from "effect/ui/html"
const template = "<html><head></head><body><div id=\"app\"><!--app-html--></div></body></html>"
const page = HtmlServer.document(template, { html: "<h1>Home</h1>", state: {}, model: undefined, failures: [], head: "<title>Home</title>", htmlAttributes: "lang=\"en\"", bodyAttributes: ""})page // => '<html lang="en"><head><title>Home</title></head><body><div id="app"><h1>Home</h1></div><script type="application/json" id="state">{}</script></body></html>'serializeState
unstableThe state as JSON that is safe inside <script type="application/json">:
< and the line separators are escaped, so the script can't end early.
Signature
declare function serializeState(state: State): string