Node.js and Bun #
@microsoft/webui exposes the Rust renderer through a platform-specific native
addon for Node.js and Bun. Load protocol.bin once, reuse the Protocol,
and pass JSON state for each render. Buffered output is a UTF-8 Buffer.
Installation #
npm install @microsoft/webui
pnpm add @microsoft/webui
yarn add @microsoft/webui
bun add @microsoft/webui
Keep optional dependencies enabled so your manager can install the matching native package. This API needs native-addon support; it is not a browser or JavaScript-only edge-runtime package.
Choose an entry point #
One npm package ships both native addons. Import runtime APIs (Protocol,
streaming, and inspect) from @microsoft/webui. Import compiler APIs
(build, prepareBuild, and bundleClient) from @microsoft/webui/build.js;
the root does not export them.
import { Protocol } from '@microsoft/webui';
import { build, type BuildOptions } from '@microsoft/webui/build.js';
Each entry loads only its own native addon when its API is used. A server that
loads prebuilt protocols does not load the compiler addon. Compiler types,
including BuildOptions, BuildResult, PreparedBuild, LazyPackFile, and
the Client* bundling/projection types, also come from /build.js; runtime
types come from the root.
For source builds or custom artifact locations, WEBUI_ADDON_PATH selects the
runtime addon (libwebui_node.dylib, libwebui_node.so, or webui_node.dll).
WEBUI_BUILD_ADDON_PATH independently selects the compiler variant. Source
builds use the same library filename in a separate target/node-build root;
packaged addons are named webui.node and webui-build.node.
Loading errors are reported by the selected API.
The webui CLI is installed from the same package as before.
Scaffold an application #
Node and Bun hosts use native frontend tooling:
webui init my-app --server node --no-interactive
cd my-app
npm install
webui app check
webui app dev
For Bun, select --server bun and restore with bun install. Native Bun
defaults to Bun for runtime package restoration; native Node defaults to npm.
--package-manager can override that choice.
Install the matching native toolchain
separately. Browser bundling and TypeScript checking use native tools, not
Node/esbuild build scripts. These hosts still require their server runtime,
the native addon, a root runtime package.json, and server/http.mjs.
Application templates and browser sources live in web/; webui.toml
selects the host. There is no scripts/ build orchestration.
Use webui app build then webui app start for production. Start verifies the
recorded host entry and protocol and does not restore packages or compile.
Serve only dist/public/ as static files. See
app commands.
Examples #
import { createServer } from 'node:http';
import { readFileSync } from 'node:fs';
import { Protocol } from '@microsoft/webui';
const protocol = new Protocol(
readFileSync('./dist/protocol.bin'),
{ plugin: 'webui' },
);
const server = createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
protocol.renderStream(
{ title: 'Home' },
(chunk) => res.write(chunk),
{ entry: 'index.html', requestPath: req.url },
);
res.end();
});
server.listen(3000);
import { Protocol } from '@microsoft/webui';
const protocol = Bun.file('./dist/protocol.bin');
const protocolData = Buffer.from(await protocol.arrayBuffer());
const runtimeProtocol = new Protocol(protocolData);
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
const html = runtimeProtocol.render({ title: 'Home' }, {
entry: 'index.html',
requestPath: url.pathname,
});
return new Response(html, {
headers: { 'Content-Type': 'text/html' },
});
},
});
API Reference #
| API | Description |
|---|---|
new Protocol(protocol, options?) | Decode and index protocol bytes once and bind the selected plugin |
protocol.render(state, options?) | Render into a UTF-8 Buffer for direct HTTP writes |
protocol.prepareState(state) | Parse an immutable, process-local native state snapshot once |
protocol.renderPrepared(state, options?) | Render a prepared snapshot without serializing or parsing it again |
protocol.renderStream(state, onChunk, options?) | Render with callbacks coalesced around a 16 KiB target before crossing into JavaScript |
protocol.streamResponse(options?) | Open a progressive streaming session that returns one Buffer per host call |
protocol.renderPartial(state, entry, requestPath, inventory) | Produce a complete partial-navigation JSON response |
protocol.renderComponentTemplates(tags, inventory) | Return on-demand template payloads |
protocol.tokens() | Return CSS token names in build order |
inspect(protocol) | Convert protocol to JSON for debugging |
Compiler APIs from @microsoft/webui/build.js:
| API | Description |
|---|---|
build(options) | Build templates into a protocol. Returns { protocol, cssFiles, componentAssetFiles, lazyPackFiles, lazyScriptsModule?, metafile?, warnings, stats } |
prepareBuild(options) | Compile once before client bundling; returns a single-use PreparedBuild |
bundleClient(options) | Run native browser bundling and state projection asynchronously; returns final files, proof and input/output metadata |
RenderOptions #
| Field | Type | Default | Description |
|---|---|---|---|
entry | string | "index.html" | Fragment ID to start rendering from |
requestPath | string | "/" | URL path to match routes against |
state accepts either an object (auto-serialized) or a pre-stringified JSON string. |
ProtocolOptions #
| Field | Type | Default | Description |
|---|---|---|---|
plugin | string | - | Handler plugin bound for the lifetime of the protocol |
Single-compilation builds #
When your client imports generated lazy or component modules and also produces a state-projection manifest, retain one compilation across client bundling:
import { prepareBuild, bundleClient } from '@microsoft/webui/build.js';
import { writeFileSync } from 'node:fs';
const prepared = prepareBuild({
appDir: './src', plugin: 'webui', modulesOut: './.webui',
});
prepared.writeModules();
const client = await bundleClient({
project: process.cwd(),
entries: { index: 'src/index.ts' },
outDir: 'dist',
});
const result = prepared.finish({ projectionManifests: [client.manifestPath] });
writeFileSync('./dist/protocol.bin', result.protocol);
bundleClient() performs bundling, source analysis and proof construction
natively. It needs no JavaScript compiler peer. project must contain the
physical inputs and output directory. outDir and manifestPath accept
project-relative paths such as ./dist and ./dist/proof.json. CSS imports
use import attributes (such as with { type: "css" }), not a "css" loader
override. Set write: false to receive final files buffers without publishing
them; a retained build still requires its proof's exact files on disk before
finalization.
The result's warnings contains typed { code, message } advisories; build
hosts should display them. Unexpected bundler warnings still fail the build.
Set parallelDynamicImports: true to request concurrent imports of eligible
dynamic targets and their additional static dependencies. Imports with
retained options and chunks that may export then keep their normal loading
semantics. This option may evaluate eligible shared dependencies independently.
The returned metadata records the actual concurrent imports.
Publish result.cssFiles and result.lazyPackFiles with the protocol as
described below. writeModules() uses modulesOut, or appDir when omitted,
preserving unchanged generated files and publishing dependencies before their
entry modules. For virtual bundler inputs, read componentAssetFiles and
lazyScriptsModule instead. lazyPackFiles also exposes the prepared payloads;
requested compression measurements are available in the final result.
prepareBuild() accepts BuildOptions. finish() accepts
projectionManifests and projectionManifestObjects, merged with any supplied
during preparation; omitting both preserves full-state behavior. Manifest
hashes and scripted-component coverage are checked before finalization.
The retained templates/CSS are a snapshot: start a new preparation when editing
them. A finish() attempt consumes the handle, even if manifest validation
fails; subsequent methods or getters throw. Native retained data is released
when consumed, or when an abandoned handle is garbage-collected.
stats.durationMs counts WebUI preparation and finalization, not time spent
in your client bundler.
Lazy template packs #
Lazy bodies need no request-time API. build() returns
their packs in lazyPackFiles; webui build writes them for you. Publish each
pack at its path, under _webui/packs/ beside the page, as an immutable
static file. When the build has lazy regions, lazyScriptsModule is the
generated lazy.webui.js, and its declaration is the lazy.webui.d.ts that
gives TypeScript entries its types without allowJs. Write both to the
directory you passed as modulesOut.
In the browser entry, import lazy.webui.js before startRuntime().
Your bundler owns chunk grouping; bare lazy is activation-only, with selective
idle warming and path prefetch available. See lazy integration.
Publish the generated files like this:
import { build } from '@microsoft/webui/build.js';
const result = build({ appDir: './src', plugin: 'webui', modulesOut: './.webui' });
for (const pack of result.lazyPackFiles) {
writeFileSync(join('dist', pack.path), pack.content);
}
const lazy = result.lazyScriptsModule;
if (lazy) {
writeFileSync(join('.webui', lazy.fileName), lazy.content);
writeFileSync(join('.webui', lazy.declaration.fileName), lazy.declaration.content);
}
Relative module specifiers in lazy.webui.js start at modulesOut, or at
appDir when you omit it. A region lists only the components that neither its
owner nor the page at startup already loads. componentModules maps a tag to a
module specifier for a component without a usable .ts or .js sibling; see
Lazy region scripts.
Each lazyPackFiles item reports its pack:
| Field | Type | Description |
|---|---|---|
fileName | string | Content-addressed file name |
content | string | JSON pack content |
path | string | _webui/packs/<fileName>, relative to the asset base |
region | string | Region identity, such as app-shell::lazy:@0 |
owner | string | Component whose template declares the region |
trigger | "intent" | "idle" | "eager" | "demand" | The region's lazy value |
hash | string | Content hash from the file name |
bytes | number | Size of content in bytes |
brotliBytes | number | Brotli size at quality 11; present only when metafile: true |
scripts | string[] | Module specifiers lazy.webui.js loads with the region |
stylesheets | string[] | Stylesheet paths, relative to the asset base, that the region loads with its pack in a css: "link" build: entries of cssFiles, including bundled chunks. Always present; empty for "style" and "module" builds, whose packs carry the CSS |
To precache a region in a service worker, cache its path, its stylesheets,
and the bundler outputs for its scripts.
Templates reference packs by the path _webui/packs/<file>, relative to the
asset base. To publish the output elsewhere, such as a CDN, pass assetBase
(ending in /) to build(), or set it per request in the render state:
protocol.render({ ...state, $webui: { assetBase: 'https://cdn.example.com/b123/' } });
The request value overrides assetBase. Rendering prefixes stylesheet links
with the base and passes it to the browser, which resolves pack and stylesheet
paths against it. Module preload hints keep their paths, because they name your
own scripts. An invalid request value throws before any output is produced.
Bundler public path #
The rendered document head carries the response's base as
<meta name="webui-asset-base" content="...">, so your entry can hand it to
your bundler before the WebUI runtime starts. The region scripts that
lazy.webui.js imports then load from the same base. With rspack or webpack,
run this first in your entry module:
__webpack_public_path__ =
document.querySelector<HTMLMetaElement>('meta[name="webui-asset-base"]')?.content
?? __webpack_public_path__;
Static imports run before the statements of the module that imports them, so if your entry has static imports, put the line in its own module and import that module first. This steers chunks that the bundler's runtime loads. With native ES module output, chunks load relative to the entry script's URL instead, so serve the entry script from the same base.
Reusing Protocol #
Load protocol.bin once and construct one Protocol for the lifetime of the
server:
const protocol = new Protocol(
readFileSync('./dist/protocol.bin'),
{ plugin: 'webui' },
);
const server = createServer((req, res) => {
const html = protocol.render(getState(req), {
entry: 'index.html',
requestPath: req.url,
});
res.end(html);
});
Protocol owns the loaded native artifact. The source Buffer can be released
or reused after construction; subsequent renders use the loaded object.
protocol.render() returns a UTF-8 Buffer so the native allocation can be
passed directly to response.end(). Call .toString('utf8') only when
JavaScript string operations are required. Use protocol.renderStream() when
the HTTP integration can make progress from callbacks; callbacks are batched
rather than invoked for every internal handler write. The callback is
synchronous and its return value is ignored. A false result from
response.write() cannot pause native rendering or wait for drain, so this
API does not provide transport backpressure. Callback exceptions abort the
render immediately and propagate to the caller.
Reusing immutable state #
When one state snapshot is rendered more than once, prepare it alongside the protocol:
const cachedState = protocol.prepareState(await loadCatalogState());
const server = createServer((_req, res) => {
res.end(protocol.renderPrepared(cachedState));
});
Preparation performs serialization and native JSON parsing once.
renderPrepared() reuses the immutable native tree and produces the same bytes
as render() for matching options. Later mutations to the source object are not
visible; create a new prepared state when request data changes.
The opaque handle is process-local and cannot be serialized. It retains the
native state tree until JavaScript garbage collection releases the handle, so
this API trades resident native memory for lower repeated-render CPU and
allocation pressure. Ordinary per-request state should continue to use
render().
BuildOptions #
Import this type from @microsoft/webui/build.js.
| Field | Type | Default | Description |
|---|---|---|---|
appDir | string | - | Path to app folder |
entry | string | "index.html" | Entry file |
css | "link" | "style" | "module" | "link" | CSS delivery strategy |
dom | "shadow" | "light" | "shadow" | Fallback for unwrapped components; Light builds retain authored Shadow islands |
cssBundle | boolean | false | Merge component stylesheets into shared chunks. Composes with css; rejected with css: "module" |
plugin | string | - | Parser plugin name (see Plugins for the available identifiers) |
components | string[] | - | External component sources |
componentAssetRoots | string[] | - | Root component tags emitted as static .webui.js ESM assets |
metafile | boolean | false | Return the build metafile: the component asset graph and the lazyPacks report. Also measures brotliBytes for each lazy pack |
componentModules | Record<string, string> | - | Module specifiers keyed by custom element tag, for components without a usable .ts or .js sibling. Written verbatim in lazy.webui.js |
modulesOut | string | appDir | Directory you write generated modules to; relative specifiers in lazy.webui.js start here |
projectionManifests | string[] | - | Projection manifest paths, merged with strict scripted-component coverage |
projectionManifestObjects | { path: string; manifest: unknown }[] | - | Already-transported manifests with logical paths anchoring root and stale checks |
cssFileNameTemplate | string | "[name].[ext]" | Emitted filename template for Link-mode CSS. Tokens: [name], [hash], [ext] |
assetBase | string | - | Public URL or path ending in / that maps to the build output. Stored in the protocol; requests override it with $webui.assetBase. See Asset base |
legalComments | "inline" | "none" | "inline" | Preserve legal CSS comments inline, or strip all comments |
theme | string | - | Design token theme JSON path or npm package name. Missing required CSS tokens fail the build (literal var() fallbacks are exempt) |
Unwrapped components default to generated open Shadow roots. Set dom: "light"
to make them global Light DOM; authored sole open Shadow roots remain Shadow.
Light CSS uses ordinary selectors, and :host, :host-context, and
::slotted fail with unsupported-light-css.
import { build } from '@microsoft/webui/build.js';
const result = build({
appDir: './src',
plugin: 'webui',
projectionManifests: ['./dist/webui-projection.json'],
});
When componentAssetRoots is set, componentAssetFiles contains stable version
4 ESM inputs: one module per asset-owned component plus a thin root entry with
static imports for its closure. Entry-reachable dependencies stay external and
asset-only records are removed from result.protocol. Pass these inputs to the
application bundler, which owns final splitting, hashes, public paths, caching,
and delivery. Component assets cannot be combined with <route>.
Set metafile: true to receive
result.metafile when the build emits component assets or lazy packs. The JSON
uses esbuild's inputs/outputs schema, root entryPoint records, and static
import-statement edges, so it can be opened directly in an esbuild bundle
analyzer. Its lazyPacks array lists every lazy pack, sorted by path, with the
fields above except fileName and content; see
Build metafile.
Manifest inputs are build-time only. The returned protocol is self-contained,
and render() does not load projection tooling. If no manifest is supplied,
the build preserves full state.
The Node API requires the platform-specific native addon. Addon resolution and
loading errors are returned directly and never trigger a CLI subprocess. Use
the webui CLI explicitly when a filesystem-oriented build is preferred.
BuildStats #
| Field | Type | Description |
|---|---|---|
durationMs | number | Build time in milliseconds |
fragmentCount | number | Total fragments |
componentCount | number | Components registered |
cssFileCount | number | CSS files produced |
protocolSizeBytes | number | Protocol binary size |
tokenCount | number | CSS tokens discovered |
Progressive Streaming #
renderStream() calls a synchronous callback and ignores its return value.
It cannot wait for response.write() backpressure. Use a progressive session
when the host needs to pace delivery or wait for boundary data.
protocol.streamResponse() inverts that. It opens a session whose methods
return bytes, so your server owns the socket and backpressure:
const session = protocol.streamResponse({
entry: 'index.html',
requestPath: '/',
});
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'X-Accel-Buffering': 'no',
});
let step = session.start(initialState);
await write(res, step.bytes);
while (!step.done) {
const boundary = step.boundary;
if (boundary) {
const state = await loadBoundaryState(
boundary.owner,
boundary.name,
boundary.key,
);
step = session.resume(boundary.instanceId, state, 'final');
} else {
step = session.advance();
}
await write(res, step.bytes);
}
res.end();
async function write(res, chunk) {
if (res.write(chunk)) return;
// An aborted client never emits 'drain', and surfaces as 'close', not
// 'error' — so waiting on 'drain' alone would hang forever.
await new Promise((ok, fail) => {
const done = (error) => {
res.off('drain', onDrain);
res.off('close', onClose);
if (error) fail(error);
else ok();
};
const onDrain = () => done();
const onClose = () => done(new Error('client disconnected'));
res.once('drain', onDrain);
res.once('close', onClose);
});
}
The same shape works behind Express, Fastify, Hapi, or a raw socket. Boundaries
are discovered at runtime through entries, reusable components, conditions, and
the selected route. A boundary-bearing subtree under <for> fails the build
with boundary-in-repeat; a whole <for> may sit inside one boundary.
For a coordinator-only head script, follow the
bundler-independent delivery contract.
Configure script URLs through your existing asset handoff; the native
StreamingSession does not depend on a bundler or read asset manifests.
The application explicitly imports @microsoft/webui-framework/streaming.js
in its own early entry and registers that entry with its bundler.
Application registrations may load later, but are required before their
components become interactive.
StreamingSession #
| Member | Description |
|---|---|
start(state) | Return { bytes, done, boundary? } through the first occurrence or terminal |
resume(instanceId, state, mode?) | Return only the pending occurrence's bytes through its checkpoint |
advance() | Return following parent bytes through the next occurrence or terminal |
update(instanceId, patch) | Return projected state bytes for a committed updatable occurrence |
A descriptor contains instanceId, declarationId, owner, name, and an
optional string or numeric key. Use those fields to load state, then pass
instanceId back to resume. A descriptor means call resume; no descriptor
with done: false means call advance; done: true means complete.
Write and flush the boundary-only resume result before waiting for more data.
advance carries the following parent content; the final step includes the
document tail. mode is "final" by default or "updatable".
An update never inserts markup or reruns hydration:
const patch = session.update(searchInstanceId, { query: 'webui' });
await write(res, patch);
An update may be written between the occurrence's resume and advance.
Sessions are single-driver and independent. Hold one per in-flight request and
stop driving it after a rendering or transport failure.