SSR Boundaries
OAS-UI is a Web Components library: components register custom elements, Shadow DOM and events at runtime in the browser. The following boundaries apply in SSR / static-generation environments.
Core rule
Do not run side-effect imports of the component library during server-side rendering
The library entry @oas-ui/ui calls customElements.define and DOM APIs, which throw in Node (no DOM), e.g. HTMLElement is not defined.
DSD route (progressive enhancement)
The SSR strategy is Declarative Shadow DOM (DSD), shipped as a first-class capability: the server outputs the static structure plus styles inside <template shadowrootmode="open">, and the browser's custom element upgrade takes over interactivity afterwards.
Shipped capabilities:
- The base class
OASElementreuses an existing declarative shadow root: when the element already has a shadow root attached by<template shadowrootmode="open">before upgrade, the constructor reuses it instead of callingattachShadow(which would throwNotSupportedErrorand break the component). - The
@oas-ui/ssrrenderer has landed: it boots a minimal DOM shim on happy-dom in Node, registers the component classes, renders per input, and serializes the shadow snapshot as DSD, returning the full host HTML string (see "Server rendering"). - True hydration: on upgrade the component detects the DSD snapshot fingerprint, skips the shadow rebuild, and only caches nodes, binds events, plus runs incremental
update(). If the snapshot structure mismatches, it falls back to a full re-render (correctness first). - A declarative data channel for data components: table / tree / select / transfer / toggle-group take
columns/data/options/itemsthrough the JSON attribute channel (property assignment reflects to the attribute in one direction; invalid JSON falls back to the empty state), and the SSR snapshot serializes the header and data rows / tree node rows / dropdown options / shuttle panel data / button groups. - Form components (DSD whitelisting): input / textarea / checkbox / radio / switch / slider / input-number / rate / auto-complete / combobox / cascader / tree-select / mentions / date-picker / time-picker / calendar / upload / color-picker / toggle-button / toggle-group / pin-input / dynamic-input / dynamic-tags / editable / form / form-item / form-list are all split into
template()(pure function) /bind()(caches nodes + binds events) /hydrate()(validates snapshot structure + takes over) — the SSR snapshot includes the skeleton and selected values; dropdown panels default to the closed state, the upload list is empty, and the textarea autosize height is the un-measured state (corrected on the first frame after hydration via rAF, same strategy as affix). - Feedback components (DSD whitelisting): alert / progress / spin / skeleton / result / backdrop / modal / drawer / popconfirm all follow the same three-part split — the visible-state components (alert/progress/spin/skeleton/ result) snapshot their full visual; backdrop renders a visible mask with
open(its default closed state self-removes on update, so it is not a snapshot scenario); modal/drawer snapshot the host skeleton in their default closed state (display: none, and a server-directvisiblesnapshot includes the full dialog); popconfirm snapshots the trigger slot plus the hidden popover. The imperative components (message / notification / toast / snackbar / loading-bar / confirm) are created dynamically by imperative APIs and do not exist in the initial DOM, so SSR is meaningless — they stay out of the whitelist. - First-frame flicker mitigation for layout-measuring components: affix / ellipsis / scroll-area defer layout writes to the first frame after upgrade when a DSD snapshot is detected (via rAF) — the snapshot is the un-measured state, the first frame after upgrade matches it (no jump), and the real layout is applied on the next frame.
- Pure-presentation and framework-container components (DSD whitelisting): the pure-presentation components badge / button-group / icon / kbd / label / link / space / visually-hidden snapshot their full visual deterministically (badge count, kbd key-cap splitting, space host inline layout styles); the floating-trigger components tooltip / popover default to the closed state and snapshot the trigger slot as-is plus the hidden bubble skeleton (content/title text is synced; positioning is computed only when triggered); the framework-level containers config-provider / app have no visual of their own and snapshot the subtree as-is with their container attributes in place (
data-theme/size, etc.), with nested children covered byinjectNestedDSD.oas-theme-editoris a dev-tool component (a theme-editing panel for development) with little SSR value — it was evaluated and excluded from the whitelist, staying client-only. oas-bottom-sheet(the mobile bottom-sheet carrier) is not whitelisted: it is a host-controlled overlay container (driven by theopenattribute). In SSR scenarios the host template embeds the initial structure (an empty panel when closed), and the component uses thepassivepassthrough mode to keep the SSR/client structure strictly identical. Server-rendering an open state is meaningless, so it stays client-only.- Backfill batches (DSD whitelisting): the highlight text-highlight component (synchronous deterministic render, pure-presentation direct output); the scheduler / gantt / barcode / resource data components (data flows through the JSON attribute declarative channel, same class as calendar / kanban / table / qrcode — synchronous deterministic rendering, no measurement dependency); form wrap-up knob / questionnaire; the five conversation components bubble / attachment (+attachment-group) / message-scroller / marker / message-row; and the workbench widget family titlebar / statusbar / inspector / action-bar plus their sub-components — pure-presentation / skeleton snapshots (overlay and input interactions default to closed / empty states), every component overriding
hydrate()for true hydration. Navigation additions: app-bar (app bar, visible structure rendered directly) and stepper (step panel, +stepper-panel). - Framework integration plugins:
@oas-ui/nuxt(a Nuxt 3/4 module) and@oas-ui/next(a Next.js App Router integration) have landed — the Nuxt module auto-configures VuecompilerOptions.isCustomElement(recognizingoas-*), injects the@oas-ui/themeglobal CSS, auto-imports therenderOasToStringSSR helper as server-only, and registers components on the client via a built-in plugin; the Next integration provides the RSC<OasComponent>that renders DSD snapshots on the server plus the<OasRegistry>client registration bootstrap (see "Nuxt (recommended)" / "Next.js (recommended)" below).
Whitelisted components can be rendered on the server directly; the rest keep the "client-only" approach below. Components outside the whitelist are intentionally excluded (imperative APIs, dev tools, host-controlled overlays, etc.), not unfinished work.
Vue (Nuxt / Vite SSR)
Use dynamic import and run it after the client mounts:
// client only
onMounted(async () => {
const { message } = await import('@oas-ui/ui')
message.success('Loaded')
})<ClientOnly>
<oas-table :columns="…"></oas-table>
</ClientOnly>React (Next.js)
Render components on the client only:
'use client'
import { useEffect, useState } from 'react'Or disable SSR with next/dynamic:
const Table = dynamic(() => import('./TablePage'), { ssr: false })Vanilla / other frameworks
The server only outputs a static placeholder; the script resource is executed by the browser to register the components.
Browser support and the DSD polyfill
Native DSD (at document-parse time, i.e. the server's response HTML) support:
| Engine | Status |
|---|---|
| Chrome / Edge | 111+ native |
| Safari | 16.4+ native |
| Firefox | Supported (verified in this repo on the Playwright Firefox 157 build; older versions not verified per-release — use the polyfill below as a fallback for legacy engines) |
Key boundary: native DSD only applies at document-parse time — the parser attaches <template shadowrootmode> as a shadow root from the server response (the table above). Fragment parsing (innerHTML / DOMParser / any runtime injection of SSR markup) does NOT auto-attach in any engine; the template stays behind as an inert node (runtime-injected SSR snapshots must handle it). Plain SSR response pages hydrate natively in every modern engine — no polyfill needed for that path.
For runtime injection, use the @oas-ui/ssr/polyfill subpath (auto-applies on import; must evaluate BEFORE @oas-ui/ui; named export hydrateDeclarativeShadowRoots(root?) for manual calls — recurses into nested DSD, idempotent, zero-hit where native support exists):
import '@oas-ui/ssr/polyfill' // first: attach template[shadowrootmode] as shadow roots
import '@oas-ui/ui' // then: register components; upgrade reuses the DSD snapshot (true hydration)Degradation without the polyfill (honest): the injected DSD templates stay inert, and components build their own shadow roots on upgrade (client-render fallback — the page works but loses the SSR first-paint advantage).
Server rendering
The @oas-ui/ssr package provides the renderer renderToString(tag, attrs, slotHTML, { locale }): on a Node server it renders a whitelisted component into a full HTML string made of the host tag plus a <template shadowrootmode="open"> snapshot. The browser renders structure and styles with no JS; loading the component library script afterwards upgrades the elements and takes over interactivity.
Note: the shadow inline styles in the snapshot reference
--oas-*theme tokens (defined on:rootin@oas-ui/theme). The page must include@oas-ui/themeas usual, otherwise the snapshot components render without colors (unresolved tokens fall back to transparent).
import { renderToString } from '@oas-ui/ssr'
const html = await renderToString('oas-button', { type: 'primary', size: 'large' }, 'Submit', {
locale: 'en',
})
// '<oas-button type="primary" size="large"><template shadowrootmode="open">…</template>Submit</oas-button>'Why async: evaluating the component classes needs a global DOM shim (class extends HTMLElement requires HTMLElement / customElements to be in place). A static import would evaluate too early to guarantee "shim first, then components", so the first call dynamically loads the component modules (after the shim is installed); modules are cached afterwards and later calls only pay for the rendering itself.
Note: DSD templates are attached by the browser's HTML parser; runtime string injection such as
innerHTMLdoes not attach them. The returned string should reach the browser through the SSR output stream (the server-rendered HTML response).Process-level side effect: on first call the renderer installs happy-dom's
document/customElements/HTMLElementand other globals ontoglobalThis(required for component class evaluation and registration). If your Node process uses another global DOM solution (other SSR libraries, test framework environments), evaluate coexistence first — the renderer throws a clear error when globals cannot be installed.
localevalues:RenderLocaleis the built-in subsetzh-CN/zh-Hant/en/ja/ko/de/fr/es/pt(alias ofpt-BR) /pt-BR/ru/ar/hi/th/uk/he/fa(ar/he/faare RTL); BCP 47 aliases are accepted (zh-TW→zh-Hant,en_US→en,zh-Hans→zh-CN). The renderer loads and registers the matching language pack on demand, so hosts do not need to callregisterLocalemanually. Thelocaletype isRenderLocale | (string & {}): built-in names keep literal autocomplete while custom locale names can be passed directly without anasassertion. A custom language pack must be registered withregisterLocale()after the firstrenderToStringcall (which installs the DOM shim), then passed by name — importing@oas-ui/i18nevaluates@oas-ui/core'sclass extends HTMLElement, so registering first in bare Node throwsHTMLElement is not defined. One render installs the shim and loads the registry. An unregistered locale triggers onedevWarnand falls back to built-inen(it never silently borrows the mutable global locale);devWarnis silent whenNODE_ENV === 'production', while the fallback behavior is unchanged.Request-scoped locale: an explicit
localeaffects only that call and its nested subtree — the renderer creates a per-call temporary<oas-config-provider locale>inside the shared DOM, mounts the target element under it and renders synchronously (the output contains no provider wrapper), then removes both in atry/finally. It never changes the global locale, and the rendering segment never broadcasts locale/translator events (the one-time i18n registry load is the only side effect). Omittinglocalekeeps the old behavior: the global locale at call time (the host-sidesetLocale()semantics are unchanged). Concurrent requests (mixed languages in a singlePromise.all, cold and hot) are fully independent with no interleaving window and require no server-side locking.
First-paint anti-flicker for system themes
The server snapshot of <oas-config-provider theme="system"> is deterministically data-theme="light"; it does not access shared storage or register media-query listeners. Client hydration corrects it using explicit stored preference > system > light fallback. When using system themes with DSD, place this synchronous bootstrap in <head> and keep its key identical to the provider's; for a provider without a key, use const key = null so only the MQL is read and storage is never accessed. It corrects the root and matching providers as they are parsed, keeping the first frame consistent with hydration. After the observer stops at DOMContentLoaded, root continues following the MQL and, with a key, corresponding localStorage events, without writing storage. Same-document reselection emits no storage event, so the script watches both requested theme and effective data-theme: a requested system write directly sets the head preference to system, while an effective change only synchronizes root without restoring stale storage or rewriting the provider in the callback. When a provider switches explicitly from system to light / dark (or a custom theme name), the script mirrors that provider's new effective theme to root and keeps following its later explicit changes (no fallback to the head preference after handover), so root cannot stay on the last system theme. While that handed-over provider stays connected with requested≠system, its effective theme is the sole root authority: MQL/storage changes still update other system providers but never pull root back to the old preference. Root returns to the MQL only when the provider disconnects or goes back to system. Every root/provider write is guarded by a current-value comparison to prevent observer self-triggering or loops. Add it only when system theming is used; the default global theme is unchanged.
<script>
;(() => {
// Use null for a provider without a key: only the MQL is read; storage is never accessed.
const key = 'oas-app-theme'
const media = window.matchMedia('(prefers-color-scheme: dark)')
const readPreference = (raw) => {
try {
const saved = JSON.parse(raw || 'null')
return saved && ['light', 'dark', 'system'].includes(saved.theme) ? saved.theme : 'system'
} catch {
return 'system'
}
}
const restorePreference = () => {
if (!key) return 'system'
try {
return readPreference(localStorage.getItem(key))
} catch {
return 'system'
}
}
let preference = restorePreference()
const effective = () => (preference === 'system' ? (media.matches ? 'dark' : 'light') : preference)
const ownsKey = (el) => (el.getAttribute('theme-storage-key') || null) === key
const matchesProvider = (el) => el.getAttribute('theme') === 'system' && ownsKey(el)
// Providers that left `system`: their later explicit light/dark takes over root (no fallback to preference).
const handedOver = new WeakSet()
const syncRoot = (theme) => {
if (theme && document.documentElement.dataset.theme !== theme) document.documentElement.dataset.theme = theme
}
// Handover authority: a still-connected handed-over provider with requested≠system and an effective theme.
// While it exists, its effective theme is the sole root authority; MQL/storage may still update other
// system providers but must not pull root back to the old preference.
const handedOverOwner = () => {
for (const el of document.querySelectorAll('oas-config-provider')) {
if (handedOver.has(el) && el.isConnected && el.getAttribute('theme') !== 'system' && el.dataset.theme) return el
}
return null
}
const apply = () => {
const theme = effective()
const owner = handedOverOwner()
syncRoot(owner ? owner.dataset.theme : theme)
document.querySelectorAll('oas-config-provider').forEach((el) => {
if (matchesProvider(el) && el.dataset.theme !== theme) el.dataset.theme = theme
})
}
apply()
// The observer only handles the first paint; MQL/storage listeners keep root synchronized for the page lifetime.
const observer = new MutationObserver(apply)
observer.observe(document.documentElement, { childList: true, subtree: true })
document.addEventListener(
'DOMContentLoaded',
() => {
apply()
observer.disconnect()
},
{ once: true },
)
// Same-document reselection emits no storage event: requested=system hands off directly; leaving `system`
// mirrors the provider's new effective theme to root and keeps following explicit changes (compare before writing).
const effectiveObserver = new MutationObserver((records) => {
for (const record of records) {
const el = record.target
if (!(el instanceof Element) || el.localName !== 'oas-config-provider' || !ownsKey(el)) continue
if (record.attributeName === 'theme') {
if (el.getAttribute('theme') === 'system') {
handedOver.delete(el)
preference = 'system'
apply()
} else if (record.oldValue === 'system' || handedOver.has(el)) {
handedOver.add(el)
const owner = handedOverOwner()
if (owner) syncRoot(owner.dataset.theme)
}
} else if (record.attributeName === 'data-theme') {
const owner = handedOverOwner()
if (owner) syncRoot(owner.dataset.theme)
else if (matchesProvider(el)) syncRoot(el.dataset.theme)
}
}
})
effectiveObserver.observe(document.documentElement, {
attributes: true,
attributeOldValue: true,
attributeFilter: ['theme', 'data-theme'],
subtree: true,
})
media.addEventListener('change', apply)
if (key) {
window.addEventListener('storage', (event) => {
try {
if (event.storageArea !== localStorage || (event.key !== key && event.key !== null)) return
} catch {
return
}
preference = readPreference(event.newValue)
apply()
})
}
})()
</script>Nuxt (recommended: the @oas-ui/nuxt module)
pnpm add @oas-ui/nuxt @oas-ui/ui @oas-ui/ssr @oas-ui/theme// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@oas-ui/nuxt'],
})The module does four things automatically:
- Vue isCustomElement: the
vite:extendConfighook registers theoas-*prefix intocompilerOptions.isCustomElement(merged with any existing function / RegExp / boolean config), so Vue no longer tries to resolveoas-*as components or warn about them - theme CSS injection:
@oas-ui/themeis appended tonuxt.options.css(the--oas-*tokens referenced by DSD snapshots become globally available); disable withoasUi: { theme: false }or pass a custom CSS entry - SSR helper auto-import (server-only):
renderOasToString/useOasRender(from@oas-ui/nuxt/ssr) are registered viaaddServerImportsand callable without an import only in Nitro contexts such as server/api — they never enter the client bundle (@oas-ui/ssrdepends on happy-dom; shipping it to the browser crashes the page). Vue pages and server components are NOT covered — use an explicitimport { renderOasToString } from '@oas-ui/nuxt/ssr'there - Client component registration: a built-in
.clientplugin runsimport('@oas-ui/ui')before the app mounts, registering every component (the@oas-ui/nextOasRegistryequivalent) —<oas-*>tags written directly in templates upgrade in place. SetoasUi: { clientRegister: false }and write your own.clientplugin for selective registration
With the module registered, pick one of the four integration paths below by page type — only path 2 collects the full DSD payoff.
Path 1: direct template tags (plain CSR, no DSD)
Write <oas-*> directly in templates: the module's isCustomElement makes Vue emit the tags as-is, and the built-in client plugin registers and upgrades them:
<template>
<oas-button type="primary">Submit</oas-button>
<oas-empty description="No data" />
</template>SSR emits the raw tags (no shadow snapshot); once the library registers in the browser, the components upgrade and take over. Zero configuration and no DSD first-paint benefit — the right choice for most application pages.
Path 2: Nitro raw-HTML routes (full DSD payoff, fixture-proven)
The browser only mounts DSD snapshots during document parsing, so the response carrying them must never go through Vue hydration — emit HTML directly from a Nitro route:
// server/api/ssr-demo.ts (renderOasToString is auto-imported, no import needed)
export default defineEventHandler(async () => {
const button = await renderOasToString('oas-button', { type: 'primary' }, 'Submit')
const empty = await renderOasToString('oas-empty', { description: 'No data' }, '', {
locale: 'en',
})
return `<div class="ssr-demo">${button}${empty}</div>`
})To serve a full page, assemble the whole HTML in the route (theme CSS in <head>, client script at the end) and register in order for true hydration:
import '@oas-ui/ssr/polyfill' // first: fallback for runtime-injected DSD (a no-op when parse-time DSD already mounted)
import '@oas-ui/ui' // then: register components; upgrade reuses the DSD snapshot (true hydration, no shadow rebuild)Worker isolation is not optional (this integration is the poisoning trigger)
The first renderOasToString call mounts a happy-dom DOM shim onto globalThis. This integration renders DSD inside the same Nitro process — if that process also serves Vue pages and the shim lands before the first Vue page render, vue-router's isBrowser (fixed at module first evaluation) misdetects a browser environment: every subsequent Vue page fails with 500 history is not defined (still reproduced on Nuxt 4.7; a process whose first render is a Vue page is immune). Production traffic makes the first request uncontrollable — run DSD rendering in a worker / subprocess / separate service (the fixture's server/dsd-worker.mjs is the complete reference); a process serving only DSD fragment routes is exempt. Also note: the DSD page's client script is a separate chunk, so the component library loads twice when Vue pages coexist.
Other production notes (the repo's packages/ssr/fixtures/nuxt fixture is the complete reference):
- Localized pages: if the client script registers locale packs (e.g.
registerLocale(en)), they must evaluate before@oas-ui/ui; otherwise hydration re-renders components in the global default language and overwrites the server-rendered snapshot text.
Path 3: v-html + renderOasToString (not viable)
Piping renderOasToString output into a Vue page via v-html conflicts with Vue hydration by design. Three symptoms (all measured):
- Unguarded top-level call in setup: the helper is a server-only auto-import and page bundles do not receive it — SSR fails immediately with 500
renderOasToString is not defined. (Earlier versions of this module registered it universally, which was worse: the 5.54 MB renderer + happy-dom landed in the client bundle and the browser died withClass extends value undefined— a blank page.) - Guarded with
import.meta.server+useAsyncData(HTML shipped via payload): the SSR response does contain the DSD, but during hydration Vue re-assignsinnerHTMLfrom the payload string — DSD templates are only consumed during document parsing, and fragment parsing (innerHTML) never mounts them — the attached shadow root is discarded and the component falls back to a full client render. - The outcome: an inert
<template shadowrootmode>is left inside the host (the browser console warns "declarative Shadow DOM is not being parsed") and the shadow carries no SSR fingerprint — functionality is rescued by CSR, and the DSD first-paint benefit is entirely lost.
Path 4: useAsyncData + payload (viable, but ends as CSR)
If you accept outcomes 2 and 3 of path 3, the snippet needs an import.meta.server guard so client-side navigations don't re-run the render:
// page setup: first paint has DSD; after hydration an inert template remains and no SSR fingerprint (see path 3)
const { data: button } = await useAsyncData('dsd-btn', async () => {
if (!import.meta.server) return '' // on client-side navigation back to this page the guard returns empty — the component disappears
const { renderOasToString } = await import('@oas-ui/nuxt/ssr')
return renderOasToString('oas-button', { type: 'primary' }, 'Submit')
})<div v-html="button" />The honest verdict: this path works (CSR rescues it), but the SSR benefit is zero and you keep the inert template and the warning — use it only when a CSR outcome is explicitly acceptable; for DSD use path 2, for simplicity use path 1.
Nuxt (manual integration, low-level)
Without the module, @oas-ui/ssr's renderToString can be called directly in a Nitro route (worker isolation still recommended — see path 2):
// server/api/ssr-demo.ts
import { renderToString } from '@oas-ui/ssr'
export default defineEventHandler(async () => {
const button = await renderToString('oas-button', { type: 'primary' }, 'Submit')
const empty = await renderToString('oas-empty', { description: 'No data' })
return `<div class="ssr-demo">${button}${empty}</div>`
})The returned HTML is emitted raw by the route (never through Vue hydration); the browser renders it on parse, then the library script takes over.
For lists, loop the calls (module caching keeps later calls at render-only cost):
import { renderToString } from '@oas-ui/ssr'
async function renderTags(rows: Array<{ status: string; label: string }>): Promise<string> {
const items = await Promise.all(
rows.map((row) => renderToString('oas-tag', { type: row.status }, row.label, { locale: 'en' })),
)
return `<div class="tags">${items.join('')}</div>`
}Next.js (recommended: the @oas-ui/next integration)
pnpm add @oas-ui/next @oas-ui/ssr @oas-ui/uiThe RSC server component <OasComponent> (from @oas-ui/next/server) calls renderToString on the server to produce a DSD snapshot, rendered through dangerouslySetInnerHTML into the SSR output stream:
// app/ssr-demo/page.tsx (Server Component)
import { OasComponent } from '@oas-ui/next/server'
export default function SsrDemoPage() {
return (
<section>
<OasComponent tag="oas-button" attrs={{ type: 'primary' }}>
Submit
</OasComponent>
<OasComponent tag="oas-divider" attrs={{ 'content-position': 'left' }}>
Divider
</OasComponent>
</section>
)
}Client registration bootstrap: mount <OasRegistry> in the layout ("use client", side-effect import '@oas-ui/ui' registers all oas-* elements globally), so every oas-* element in the app upgrades and the components take over interactivity. Next 16 server rendering is safe — see the note below:
// app/layout.tsx
import { OasRegistry } from '@oas-ui/next'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<OasRegistry>
<html lang="en">
<body>{children}</body>
</html>
</OasRegistry>
)
}Low-level capability: renderOas(tag, attrs, slotHTML, opts) (from @oas-ui/next) is a pure-logic wrapper of renderToString (attrs values support string | number | boolean and are serialized automatically); OasComponent's slotHTML prop accepts raw HTML directly (children, when a string or a ReactNode, is serialized automatically).
Next 16: OasRegistry is SSR-prerender safe (browser-guarded dynamic import)
Although OasRegistry is marked "use client", Next 16 App Router still evaluates Client Component modules on the server for the first request / prerender. The adapter now performs a browser-guarded dynamic import at module-evaluation time (if (typeof window !== 'undefined') void import('@oas-ui/ui')): on the server there is no DOM, so the guard skips and the library entry is never evaluated (no more HTMLElement is not defined); on the client the components still register during module evaluation — earlier than hydration, not deferred to useEffect. Mount <OasRegistry>{children}</OasRegistry> in the root layout as-is.
For non-default languages, register locale packs with a static import (synchronous module-evaluation time; the dynamic @oas-ui/ui import resolves at least one microtask later, so registration precedes component upgrades within the same client module graph — and in practice across chunks too, since the ui bundle is far larger than the boot code, though that is bundler behavior rather than a language guarantee; the fixture additionally settles readiness via customElements.whenDefined). Do not put locale registration in a useEffect dynamic import racing against the library — see packages/ssr/fixtures/next/app/oas-client-boot.tsx).
Note: DSD templates are attached by the browser's HTML parser — the initial SSR is applied by parsing the server output stream; client-side soft navigation (RSC flight rebuild) injects via
innerHTML, which does not attach DSD. At that point the components are already registered on the client (OasRegistry /OasClientBoot) and take over via custom-element self-rendering — this is the progressive-enhancement model.
Next.js (manual integration, low-level)
// app/ssr-demo/page.tsx
import { renderToString } from '@oas-ui/ssr'
export default async function SsrDemoPage() {
const button = await renderToString('oas-button', { type: 'primary' }, 'Submit')
const divider = await renderToString('oas-divider', { 'content-position': 'left' }, 'Divider')
return (
<section
dangerouslySetInnerHTML={{ __html: `<div class="ssr-demo">${button}${divider}</div>` }}
/>
)
}The RSC renders on the server; the literal from dangerouslySetInnerHTML goes into the SSR output stream and the browser parser attaches the DSD templates.
Caching and concurrency (host-side recipes)
- Output is safely cacheable:
renderToStringoutput is a deterministic function of its inputs (guarded byte-for-byte by the full-whitelist snapshot determinism gate), so same-source fragment or full-page caching never serves stale-wrong HTML. A cache key must include at least: tag + a normalized attribute sequence (attribute order affects output bytes — use the serialization order or a normalized sort) + light DOM + the effective locale + the snapshot version (the output embedsdata-oas-ssr-v, so stale entries from an upgraded library are detectable). - Do not cache time-dependent components (or bucket by time granularity):
oas-relative-time/oas-countdown/oas-calendar/oas-date-picker/oas-gantt/oas-schedulerrender output that depends on the render moment (relative-time text, the today line, default view dates) — caching freezes the clock. All other whitelisted components render time-independently. - No built-in caching or process architecture: fragment caching (including render-at-write), CDN orchestration, and worker pools are the host's territory — the same boundary mainstream framework render libraries keep (the renderer stays a stateless pure function). Hosts scale with a
node:worker_threadspool or multiple replicas: the renderer has no cross-request mutable state (i18n registry loading is an idempotent one-time side effect), and each worker's process memory is naturally isolated. - When concurrency is needed: rendering is synchronous CPU work with no I/O waits. Ordinary fragments (message-row scale, ~1.4 ms) are fine on a single process; a thousand-row table measured ~139 ms in a single sample and blocks the event loop — scale processes per the recipe above at high QPS; low QPS needs nothing.
Whitelist and boundaries
- Whitelist (pure-presentation components, declarative-data components, the layout-measuring pilot, form components, feedback components, data-display components, navigation/layout components, pure-presentation and framework-container components, navigation additions (app-bar app bar + stepper step panel), the highlight text-highlight component, backfill batch (scheduler / gantt / barcode / resource data components), backfill batch 2 (form wrap-up knob / questionnaire, the five conversation components, and the workbench widget family), oas-kanban (data family), and the final nine-component batch (remaining conversation / form / feedback / data / navigation standalone components) — 177 tags in total):
oas-button,oas-tag,oas-tag-group,oas-compact,oas-empty,oas-divider,oas-text,oas-title,oas-paragraph,oas-table,oas-kanban,oas-affix,oas-ellipsis,oas-scroll-area,oas-tree,oas-select,oas-input,oas-textarea,oas-checkbox,oas-checkbox-group,oas-radio,oas-radio-group,oas-switch,oas-slider,oas-input-number,oas-rate,oas-auto-complete,oas-combobox,oas-cascader,oas-tree-select,oas-mentions,oas-date-picker,oas-time-picker,oas-calendar,oas-upload,oas-transfer,oas-color-picker,oas-toggle-button,oas-toggle-group,oas-pin-input,oas-dynamic-input,oas-dynamic-tags,oas-editable,oas-form,oas-form-item,oas-form-list,oas-array-table,oas-alert,oas-progress,oas-spin,oas-skeleton,oas-skeleton-item,oas-result,oas-backdrop,oas-modal,oas-drawer,oas-popconfirm,oas-card,oas-avatar,oas-avatar-group,oas-image,oas-qrcode,oas-watermark,oas-collapse,oas-collapse-item,oas-collapsible,oas-descriptions,oas-descriptions-item,oas-timeline,oas-timeline-item,oas-list,oas-list-item,oas-carousel,oas-statistic,oas-countdown,oas-relative-time,oas-chart,oas-code,oas-equation,oas-log,oas-masonry,oas-comment,oas-marquee,oas-number-animation,oas-gradient-text,oas-aspect-ratio,oas-virtual-list,oas-json-viewer,oas-diff-viewer,oas-tabs,oas-tab-panel,oas-bottom-navigation,oas-pagination,oas-steps,oas-segmented,oas-breadcrumb,oas-anchor,oas-back-top,oas-menu,oas-dropdown,oas-context-menu,oas-menubar,oas-navigation-menu,oas-toolbar,oas-scope-bar,oas-command,oas-tour,oas-hover-card,oas-splitter,oas-flex,oas-page-header,oas-float-button,oas-speed-dial,oas-layout,oas-header,oas-sider,oas-content,oas-footer,oas-sidebar,oas-container,oas-grid,oas-grid-item,oas-badge,oas-button-group,oas-icon,oas-kbd,oas-label,oas-link,oas-space,oas-visually-hidden,oas-tooltip,oas-popover,oas-config-provider,oas-app,oas-app-bar,oas-stepper,oas-stepper-panel,oas-highlight,oas-scheduler,oas-gantt,oas-barcode,oas-resource,oas-knob,oas-questionnaire,oas-bubble,oas-attachment,oas-attachment-group,oas-message-scroller,oas-marker,oas-message-row,oas-prompt-input,oas-titlebar,oas-traffic-lights,oas-statusbar,oas-statusbar-item,oas-inspector,oas-inspector-tabs,oas-inspector-section,oas-inspector-row,oas-action-bar,oas-action-bar-button,oas-action-bar-well,oas-statistic-well,oas-task-progress-well,oas-transport-well,oas-music-well,oas-message-actions,oas-tool-call,oas-swatch,oas-picker,oas-pull-refresh,oas-notice-bar,oas-image-group,oas-swipe-cell,oas-index-bar,oas-floating-panel,oas-schema-form. - Calling
renderToStringwith a non-whitelisted tag throws an explicit error; there is no silent fallback. - Runtime boundary: the published artifact of
@oas-ui/ssr(dist/) itself does not depend on anynode:built-in module (only a singleprocess.env.NODE_ENVread, which Edge runtimes polyfill), but its runtime dependency happy-dom has no browser/edge conditional build — its implementation statically imports about 14 Node built-in modules (vm/crypto/stream/buffer, etc.) plus the CJSwspackage, so Edge bundlers fail out of the box. Deploying on Edge is integration work (bundler alias/stub or swapping the DOM shim) and needs a platform CPU budget check (a thousand-row table renders in ~139 ms in one measurement); test on the target platform before shipping. Node.js is the only first-class supported server runtime. - The imperative components (message / notification / toast / snackbar / loading-bar / confirm) are created dynamically by imperative APIs (
document.createElementappended to a floating layer), so no instance exists in the initial DOM and SSR is meaningless — they stay out of the whitelist and remain client-only;confirm()reuses theoas-modaltag (whitelisted), but theconfirm()call itself is still a client-side behavior. oas-theme-editor(a dev-tool component, a theme-editing panel for development) has little SSR value — it stays out of the whitelist and remains client-only.- Other non-whitelisted components: (1) sub-components (e.g.
oas-menu-item/oas-dropdown-group/oas-toolbar-toggle) are carried by their parent —renderToStringignores nested non-whitelisted tags, so they need no separate entry;oas-swatch-groupremains listed as a sub-component (group selection semantics); (2) the host-controlled overlay containeroas-bottom-sheetabove stays client-only; (3) all other standalone components are now covered, includingoas-index-bar/oas-picker/oas-pull-refresh/oas-notice-bar/oas-swipe-cell/oas-swatch/oas-image-group/oas-message-actions/oas-tool-call. Coverage is guarded bypackages/ssr/src/whitelist-coverage.test.ts: a new component that is neither whitelisted nor listed as intentionally non-SSR turns the gate red. oas-table/oas-tree/oas-select/oas-transfer/oas-toggle-grouptakecolumns/data/options/itemsthrough the JSON attribute channel (property assignment reflects to the attribute; invalid JSON falls back to the empty state), and the SSR snapshot includes the header and data rows / tree node rows / dropdown options / shuttle panel data / button groups.- Form components: dropdown-panel components (auto-complete / combobox / cascader / tree-select / mentions / date-picker / time-picker / color-picker) snapshot the closed state (the panel skeleton carries no popup content; the browser opens it on interaction after upgrade); upload snapshots the empty list; the textarea autosize height is the un-measured state (corrected on the first frame after hydration via rAF).
- Data-display components: pure-presentation components (card / avatar / qrcode / watermark / descriptions / statistic / masonry / comment / gradient-text / aspect-ratio and the sub-components collapse-item / descriptions-item / timeline-item / list-item) snapshot the full visuals; chart / code / equation are synchronous deterministic renders (SVG paths, regex highlighting, and the LaTeX subset are pure computation — no canvas and no async work), so the snapshot carries the complete graphics and highlighting; dynamic components (carousel / countdown / number-animation / marquee) snapshot the initial frame / initial value (carousel syncs the transform and indicators from
index, countdown renders the full initial value, number-animation renders the target whenduration=0or the initial value otherwise) and the browser takes over animation and timers after upgrade; virtual-list snapshots the first-screen window rows atscrollTop=0plus top/bottom padding placeholders (the window is computed purely fromheight/item-height/bufferattributes, not scroll measurement), and the window recomputed from the same attributes after upgrade is identical; log adopts the snapshot rows incrementally and marquee re-syncs its clone group idempotently — neither duplicates DOM. - Navigation/layout components: static-structure components (tabs / steps / pagination / breadcrumb / segmented / flex / page-header / container / grid / splitter, etc.) snapshot their full structure; floating-trigger components (dropdown / context-menu / hover-card / command / tour / speed-dial) default to the closed panel and snapshot the trigger skeleton (a server-direct
opensnapshot includes the full overlay), with the browser opening them on interaction after upgrade; visible-menu components (menu / menubar / navigation-menu / toolbar) snapshot the menu structure (submenus default to collapsed). - Pure-presentation and framework-container components: the pure-presentation components badge / button-group / icon / kbd / label / link / space / visually-hidden snapshot their full visuals (badge count, kbd key caps, space host inline layout styles); tooltip / popover default to the closed state and snapshot the trigger slot plus the hidden bubble skeleton (content/title text is synced; positioning is computed only when triggered); config-provider / app snapshot the subtree as-is with their container attributes in place, with nested children covered by
injectNestedDSD. - Nested recursive serialization: whitelisted child components upgraded in the light DOM (form > form-item > oas-input, tabs > tab-panel, descriptions > descriptions-item, layout > sider/header, grid > grid-item, timeline > timeline-item, etc.) are recursively wrapped into nested
<template shadowrootmode="open">blocks (including the child fingerprint) inserted at the start of each child's content — child shadow content (label text, etc.) is visible without JS, and both parent and child go through true hydration by fingerprint after upgrade. Child tags are loaded on demand before rendering (non-whitelisted children are left as raw markup); the light DOM part is emitted from the processedel.innerHTMLso component light-DOM sync (e.g. tabs hiding inactive panels, collapse open state) is preserved. - Final whitelist batch (nine components): conversation
message-actions/tool-call, formswatch/picker, feedbackpull-refresh/notice-bar, dataimage-group/swipe-cell, and navigationindex-bar. Snapshot structure is driven purely by attributes: picker derives its columns, selection and initial scroll position fromvalue(no measurement — without JavaScript the columns still scroll natively, but selection mapping/write-back does not run, so the snapshot only shows the initial selection); swipe-cell renders the content layer at offset 0 and never drops a host-providedopenbecause the SSR width is 0 (width is corrected after upgrade); index-bar reuses the snapshot section/letter nodes (header UIDs stay stable) and keeps the user-selected section when a programmatic jump target is unreachable (no secondoas-change); image-group collects child images synchronously insideupdate(). notice-bar setsaria-live="off"while auto-rotating items (so it does not interrupt screen readers) andpolitefor a single item / reduced-motion; the SSR pass cannot evaluateprefers-reduced-motion, so a multi-item snapshot always carriesaria-live="off"and converges to the real preference after upgrade. notice-bar'sscrollablemode also does not materialize its embedded<oas-marquee>during SSR: the renderer serializes the host light DOM only, so the snapshot keeps the single default-slot projection (probe) and hydrates the marquee on upgrade — otherwise the source copy plus the marquee clone would both render as plain content (duplicated text, doubled bar height, broken overflow clipping). Connected timers and document/scroll/gesture listeners are cleaned up on disconnect and their cleanup is re-registered on reconnect; an in-flight gesture is not resumed across a detach (it is treated as cancelled: rebound, zero events); one interaction dispatches exactly one event. - The snapshots of the layout-measuring components (affix / ellipsis / scroll-area) are the un-measured state (happy-dom reports all-zero layout), the first frame after upgrade matches the snapshot, and the real layout is applied on the next frame — this is the intended semantics of the flicker mitigation.
- True hydration: upgrade skips the shadow rebuild (DOM references are kept), only caching nodes, binding events, and running incremental
update(); a missing or mismatched snapshot fingerprint version (data-oas-ssr-vvs the runtimeSSR_SNAPSHOT_VERSION) or a structure mismatch falls back to a full re-render.
Why
customElements.definerequires a real DOM.- Shadow DOM styles and layout depend on browser rendering.
- Event dispatch (
oas-changeand other CustomEvents) only matters in the browser.
A DSD static snapshot solves progressive enhancement ("structure visible without JS"); interactivity is still handled by the browser runtime, so the customElements.define and event-dispatch boundaries are unchanged.
Three-line setup (client)
<link rel="stylesheet" href="https://unpkg.com/@oas-ui/theme@2/index.css" />
<script src="https://unpkg.com/@oas-ui/ui@2/dist/cdn.js"></script>Testing
- Unit tests run in happy-dom (a simulated DOM); a dedicated regression case covers the base class reusing an existing declarative shadow root.
- e2e tests run in real Chromium and also run axe accessibility audits.
- DSD static-page e2e: a static page is generated with
renderToStringat build time, verifying structure and styles are visible without JS, upgrade raises noNotSupportedErrorand no console errors, screenshots before/after upgrade show no flicker, and events are dispatchable. - This docs site (Vitepress) is an SSR site: demo pages dynamically import components after
onMounted, serving as an SSR boundary regression case.