Skip to content

Server Rendering and Hydration ​

@litsx/ssr renders Litsx component trees to HTML with Declarative Shadow DOM, scoped-element metadata, suspense stabilization, and a matching hydration payload.

Start with the SSR template ​

sh
npm create litsx-app my-ssr-app -- --template ssr

The scaffold includes the server document renderer, a browser registration entry, and local development wiring.

To add SSR to an existing Litsx 1.x project:

sh
npm install @litsx/ssr

Two kinds of component in an SSR tree ​

An SSR page can combine async server components and hydratable web components:

Async server componentHydratable Litsx component
AuthoringDefault-exported async PascalCase functionOrdinary compiled Litsx component
Authored return valueJSX or a Lit html templateJSX describing the component content
SSR outputSerialized HTML; hydratable descendants retain their hydration markers and metadataCustom-element host and rendered HTML, with hydration markers and metadata
ExecutionServerServer render, then browser updates
InteractivityCompose interactive child componentsState, events, refs, and browser lifecycle
HydrationThe function itself is not a hydration rootThe host participates in hydration

The compiler lowers authored JSX into Lit templates and SSR runtime calls. The SSR renderer then serializes the resolved tree to HTML, preserving the markers needed to hydrate interactive descendants. JSX is source syntax, not the HTML response.

Use server components to await page data and compose templates. Put browser interactions in ordinary Litsx components rendered inside those templates. Adding async changes the component's role; it is not a way to await data inside an interactive component's render function.

Async server components ​

The compiler recognizes a default-exported async PascalCase function that returns JSX (including fragments) or a Lit html tagged template (TemplateResult). Here, html means Lit template syntax, not a string containing raw HTML. A function whose only return is "<main>...</main>" is not recognized as a server component. Import the component with a default import when composing another server template.

tsx
// ProductPage.tsx — compiled for SSR
import { ProductCard } from "./ProductCard.tsx";
import { loadProduct } from "./data.js";

export default async function ProductPage({ productId }) {
  const product = await loadProduct(productId);

  return (
    <main>
      <h1>{product.name}</h1>
      <ProductCard product={product} />
    </main>
  );
}

Render it through the same document API:

tsx
import { renderDocument } from "@litsx/ssr";
import ProductPage from "./ProductPage.tsx";

const result = await renderDocument(<ProductPage productId="trail-shoe" />, {
  title: "Product page",
  clientEntry: "/src/main.js",
});

The SSR renderer awaits the function and resolves its returned tree, including nested server components. ProductCard remains a hydratable web component; ProductPage does not become a browser custom element. Keep server data access in server modules and register the interactive components in the browser entry.

These examples require the Litsx SSR compiler integration. Returning JSX from an async function alone does not replace that compilation step. The authored-entry loader is available when a build script starts from source files.

Returning Lit templates ​

A server component can also return a plain Lit template. Declare the constructors for custom-element tags in a static Component.elements map so SSR can resolve them locally:

js
// ProductPage.js — compiled for SSR
import { html } from "@litsx/ssr";
import { ProductCard } from "./ProductCard.js";
import { loadProduct } from "./data.js";

export default async function ProductPage({ productId }) {
  const product = await loadProduct(productId);
  return html`
    <main>
      <h1>${product.name}</h1>
      <product-card .product=${product}></product-card>
    </main>
  `;
}

ProductPage.elements = {
  "product-card": ProductCard,
};

Lit template bindings still apply: .product passes a property, while normal interpolated text is escaped. JSX bindings are inferred by the compiler; a plain Lit template uses explicit Lit binding syntax.

The compiler resolves direct imports, constant aliases, and static object-member entries that identify one stable constructor. Ambiguous dynamic entries require explicit hydratable metadata or an adapter. The map provides the SSR registry; third-party modules without hydratable metadata or self-registration still need explicit browser registration.

The SSR lifecycle ​

The server render and the browser lifecycle are separate stages:

  1. Initialize and load. Establish the server DOM environment, then load SSR-compiled components and resolve the local element registry.
  2. Resolve the server tree. Create a request execution context, await server components, and resolve their JSX or Lit templates.
  3. Render component hosts. Resolve constructors from the nearest scoped registry without globally registering them. Evaluate component renders and SSR-safe hooks, emit styles and Declarative Shadow DOM, and collect root props and hook state.
  4. Stabilize. Await pending soft-suspense work and retry until rendering settles or the pass limit is reached. Render code can run more than once; keep it free of mutations that must happen exactly once.
  5. Serialize. Capture library resource snapshots after the final pass and assemble HTML, preloads, hydration data, and the document bootstrap.
  6. Hydrate in the browser. Install hydration support, prepare resource snapshots and root payloads, run the registration entry, and load discovered client modules. Components adopt the existing server DOM and enter their browser lifecycle.

Server rendering does not mount a live browser component. Do not rely on connection effects to produce the initial HTML or to fetch data needed by that HTML.

Hook behavior on the server ​

This table describes hooks inside ordinary hydratable components during SSR. Async server components should use await for data and compose those components for stateful browser behavior; hooks are rejected inside async render functions.

API or behaviorDuring SSR
useState, useReducedStateResolve render state and collect hydration state; dispatch does not schedule a browser update
useMemoValue, stable callbacks, useRefResolve render-time values; refs do not receive browser DOM nodes
useOnConnectConnection setup and its cleanup do not run
useAfterUpdate, useOnCommitBrowser effects do not run
useExposeImperative handle factories do not run
useExternalStoreReads getServerSnapshot() when provided, otherwise getSnapshot(); does not subscribe
useTransition, startTransitionRun the callback immediately without a pending browser transition
useDeferredValueUses the current value without deferral
Event handlers and DOM refsAttach in the browser during hydration, rather than executing on the server

Use useOnConnect for subscriptions, observers, and browser-only setup. Use useAfterUpdate or useOnCommit for work that needs the browser's rendered DOM. Keep browser globals such as window out of module initialization and server render code.

See the lifecycle hook reference for the browser contracts.

DOM initialization and html ​

The main @litsx/ssr entry initializes Lit's server DOM environment before evaluating its Lit-dependent runtime. It also re-exports Lit's html tag, so lower-level framework code can obtain both from the same safe entry:

js
import { html, renderToString } from "@litsx/ssr";

const result = await renderToString(html`<app-root></app-root>`);

This is sufficient when @litsx/ssr loads before application components. A framework that may evaluate Lit, LitElement, or compiled components first must establish the DOM identity at its earliest server entry:

js
import "@litsx/ssr/install-dom-shim";

const { startServer } = await import("./server.js");
await startServer();

The bootstrap import is synchronous and idempotent, preserves an existing DOM environment, and is a browser no-op. Keep component loading behind that import boundary: class hierarchies created against a different HTMLElement identity cannot be repaired afterwards. Do not import Lit's internal DOM-shim subpath directly.

Render a document ​

tsx
import { renderDocument } from "@litsx/ssr";
import { ProductCard } from "./ProductCard.tsx";

const result = await renderDocument(
  <ProductCard product={product} />,
  {
    title: "Product page",
    clientEntry: "/src/main.js",
  },
);

return new Response(result.document, {
  headers: { "content-type": "text/html; charset=utf-8" },
});

The matching browser entry registers the compiled elements:

js
const { defineProductElements } = await import("./ProductCard.tsx");
defineProductElements();

When clientEntry is present, renderDocument(...) emits the standard hydration bootstrap. It also returns the rendered fragment, module preloads, hydration data, and normalized document-shell fields for framework adapters.

Lower-level rendering ​

Use renderToString(...) when your framework owns the document shell. Use renderToStream(...) when the response must be exposed as a Web ReadableStream<string>.

Streaming is a transport shape over the completed SSR result: Litsx waits for suspense retries to settle before emitting chunks. It is not progressive Suspense streaming.

Suspense retries and failures ​

An async server component's await is resolved before its returned template is serialized. Soft-suspense reads in the component tree can also make SSR wait and retry. A fallback does not imply that the response progressively sends fallback HTML followed by replacement content.

maxSuspensePasses bounds soft-suspense retries and defaults to 25:

tsx
const result = await renderDocument(<ProductPage productId="trail-shoe" />, {
  clientEntry: "/src/main.js",
  maxSuspensePasses: 25,
});

If rendering does not converge, the renderer throws an error with name: "LitsxSsrMaxSuspensePassesError", code: "LITSX_SSR_MAX_SUSPENSE_PASSES_EXCEEDED", and maxPasses. Handle it at the server response boundary. The pass limit counts retries; it is not a timeout for a pending fetch or promise.

See Suspense and errors for the authored boundary primitives.

Authored entries ​

Build scripts can render from an authored entry without importing a constructor first:

js
import { createEntry, renderDocument } from "@litsx/ssr";

const result = await renderDocument(createEntry({
  root: process.cwd(),
  clientEntry: "./src/main.js",
  elements(loader) {
    return {
      "app-root": async () => (await loader("./src/App.tsx")).App,
    };
  },
  render({ html }) {
    return html`<app-root></app-root>`;
  },
}));

The html argument passed to render(...) is the same initialized tag exposed by the package entry; authored entries do not need a separate lit import.

Document templates ​

There are two document-shell extension points. A template(context) callback in renderDocument(value, options) assembles a shell around an already rendered value. An authored entry can instead provide template: "./index.html", resolved relative to root.

For an authored HTML file:

html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title><!--app-title--></title>
    <!--app-head-->
  </head>
  <body>
    <main><!--app-html--></main>
    <!--app-bootstrap-->
  </body>
</html>
MarkerContract
<!--app-html-->Required; receives the rendered application fragment
<!--app-title-->Optional; receives the escaped document title
<!--app-head-->Optional; receives head content, preloads, and hydration data
<!--app-bootstrap-->Optional; receives the bootstrap script

When the head or bootstrap marker is absent, the renderer inserts that content before </head> or </body> respectively, if the closing tag exists. These shell templates wrap the result; async server components produce the application templates inside it.

For a custom shell callback, reuse html, modulePreloads, hydrationScript, and bootstrap from its context. Escape any dynamic values you interpolate into raw document strings yourself.

Light DOM ownership and hydration ​

An empty registered Light DOM host in an authored entry is rendered automatically on the server:

js
elements(loader) {
  return {
    "app-root": async () => (await loader("./src/App.tsx")).AppRoot,
  };
},
render({ html }) {
  return html`<app-root></app-root>`;
}

This gives hydration existing child nodes to adopt instead of creating the Light DOM tree during the first browser update. An explicit renderLight() remains valid and is not duplicated. A host with authored children is left alone because those nodes may be intentional projected content.

The Vite plugin also infers nested Light DOM boundaries when a project-local pure Lit template consumes an imported Litsx child. Server and browser output share the same child-owned Lit part, preserving descendant node identity, event bindings, and later updates through hydration.

There is one context boundary to keep explicit: a context provider authored inside an uncompiled pure Lit LightDomMixin template does not enter the Litsx SSR provider stack for its initial value. Provider updates after hydration use the normal composed @lit/context protocol.

Request state and resource snapshots ​

createExecutionContextKey(...) and getCurrentExecutionContext() provide request-local state shared by nested server components and stable across suspense retries.

Each public render call creates a fresh execution context internally. It is isolated from concurrent renders; options.context configures SSR metadata such as idPrefix and does not inject the execution context. Use typed context keys for request-local values rather than a mutable module-level variable.

Library runtimes with a global resource cache can use useSsrResourceSnapshot({ key, capture, restore }). The server captures serializable state after the final render pass; hydration restores it before component registration can trigger the first client render. This API is for infrastructure libraries, not manual application bootstrap code.

Preserving the hydration contract ​

Keep Lit comment markers, Declarative Shadow DOM, and data-litsx-root attributes in the HTML delivered to the browser. Hydration uses those boundaries to match the payload to existing nodes. Do not replace the rendered roots or rearrange projected children before hydration.

Root props, serialized hook state, and resource snapshots must be JSON-serializable. Pass the client only the data it needs: server-only objects such as database connections belong in server code or the request execution context.

The standard clientEntry flow installs hydration support through @litsx/ssr/hydration; applications do not need a separate manual Lit hydration patch. Frameworks that own the bootstrap can use hydratePage(...) and the registerHydrationModule(...) / registerHydrationModules(...) helpers from that entry. Registration helpers discover exported hydratable component classes; they do not hydrate the DOM by themselves. Share one Lit installation between components and the hydration runtime.

Scope ​

The supported interoperability path covers registered pure Lit and Litsx trees whose constructors and boundaries are visible to the compiler or SSR elements map. Arbitrary opaque third-party Lit components with unrelated light/shadow DOM and hydration behavior do not automatically acquire Litsx SSR semantics.