Documentation / Reference
Browser & Native
Mount or prerender a browser app, pass reactive inputs from its host, run shared views in a native window, and read the host surface.
Mount into the DOM
The browser adapter translates Refract views into DOM nodes and CSS. Use refract_web::mount to create the initial DOM, or refract_web::hydrate to adopt a prerendered view. Both return a Mount that owns the app’s state, event listeners, and updates.
The default mount creates an open ShadowRoot on an unused host element. Set shadow: false in MountOptions for light DOM. For an embedded app, the containing framework owns the host element while Refract owns the UI inside it.
let mounted = refract_web::mount(
host_element,
counter(0),
refract_web::MountOptions::default(),
)?;
// Keep the mount alive for the lifetime of the UI.
// mounted.dispose() releases nodes, listeners, and state.Keep the returned Mount alive. Dropping it or calling dispose releases the UI. A disposed shadow mount leaves its ShadowRoot attached; mount needs a fresh host, while hydrate can reuse an empty shadow root.
Prerendering
Render the initial browser view during a release build so the app is visible before JavaScript and WebAssembly load. The existing Refract CLI evaluates an export from the app’s WASM module and writes HTML; the build does not need another app binary, Node.js, or a browser.
Prerendering evaluates initial state and view bodies without starting effects. Timers, subscriptions, and asynchronous work registered with cx.effect start after the browser hydrates the view. This is an opt-in build feature for web; refract dev is unchanged and native builds do not support --prerender.
refract build --release --prerenderExport and hydrate the initial view
Add refract_web::export_prerender!(application()) at module scope in the app’s WASM entry module. Use the same initial view in the browser’s hydrate call. New projects created by the updated CLI include this wiring.
Place <!--refract:app--> exactly once inside the host in public/index.html, for example <main id="app"><!--refract:app--></main>. The build replaces that marker with the rendered fragment. By default the fragment includes base styles and a declarative shadow root, which the browser displays before the runtime starts.
Pass PrerenderOptions as the macro’s second argument to include application CSS through styles, set a style_nonce, or select light DOM with shadow: false. Keep the prerender and browser shadow policies consistent so the initial page and the live app use the same boundary.
// At module scope in the WASM entry module:
refract_web::export_prerender!(application());
// In the browser entry point:
let mounted = refract_web::hydrate(
host_element,
application(),
refract_web::MountOptions::default(),
)?;
// Keep mounted alive for the lifetime of the UI.
// mounted.hydrated() reports whether the snapshot was adopted.Hydration recreates Rust state and event handlers, checks the initial tree, and reuses matching DOM nodes before committing effects. A mismatch gets a fresh mount; without a snapshot, hydrate mounts normally. Pre-hydration events are not replayed, and edited form values trigger a fresh mount to keep the DOM and Rust state consistent.
Use the build artifacts
The default web output is dist/web/. Serve it directly, or embed the snapshot in another application and load the matching JS/WASM assets. Keep the snapshot and runtime from the same build together.
For Next.js and other bundlers, import the generated module with import snapshot from "./generated/app.prerender.mjs". Its default export is a frozen { version: 1, html: string } object. Importing it does not load WASM or access browser APIs, so it can be used during server rendering.
The module contains build data, not a React component. A framework adapter renders snapshot.html into an opaque host boundary and starts the Refract app on the client. React should not reconcile the nodes owned by Refract. Handle both parsed declarative shadow roots on initial page loads and inert templates on client navigation, and release the mount during cleanup.
The counter on this website uses that integration. The website build generates its snapshot and matching runtime before Next.js compiles the pages. These generated assets are ignored by Git; building from a fresh checkout requires the Rust toolchain.
| Artifact | Purpose |
|---|---|
index.html | The app’s public entry page with the initial view inserted at the host marker. |
app.html | An embeddable HTML fragment containing the initial view and styles. |
app.prerender.mjs | An importable ES module whose html field contains the same fragment as app.html. |
app.prerender.d.mts | TypeScript declarations for the snapshot module. |
pkg/ | The generated JS loader and WASM module used to make the app interactive. |
Keep initial inputs deterministic. During prerendering the surface has no viewport or location, an empty title, and no host capabilities. Browser-dependent initial views may remount during hydration. Browser imports called during rendering fail the build; move that work into effects. A failed build preserves the previous successful distribution.
Pass reactive inputs from the host
An embedding application can supply changing state such as a color scheme, locale, or selected record. Create ordinary State values in an initializer that receives the app’s own Runtime, then return the root view and the writable handles needed by the host. The initializer runs once before the first view evaluation.
Share read-only Read handles through an environment object. Descendant views retrieve that object with cx.object and subscribe to individual fields with cx.read. This uses the same state and dependency tracking as the rest of the app. The adapter’s Surface continues to supply standard observations such as viewport and location; host inputs carry application-specific values.
use refract::prelude::*;
use std::rc::Rc;
struct HostInputs {
dark: Read<bool>,
}
#[derive(Clone)]
struct InputHandles {
dark: State<bool>,
}
struct ThemeLabel;
impl View for ThemeLabel {
fn body(&self, cx: &mut ViewContext<'_>) -> Result<impl View, ViewError> {
let inputs = cx.object::<HostInputs>()?;
let label = if cx.read(&inputs.dark) { "Dark" } else { "Light" };
Ok(text(label))
}
}
fn initialize(rt: &mut Runtime) -> (impl View, InputHandles) {
let dark = State::new(rt, false);
let root = ThemeLabel.environment_object(Rc::new(HostInputs {
dark: dark.read_only(),
}));
(root, InputHandles { dark })
}Publish changes without remounting
Call mount_with_inputs(host, options, initialize) to receive an InputMount<InputHandles>. Keep it alive for the UI’s lifetime. Its inputs() method exposes the returned handles; mount() exposes the ordinary mount API, including diagnostics and disposal.
Forward host changes through update_inputs. Each call queues one mutation batch in the owning runtime; success means the update was admitted, not that it has painted. Use set_if_changed to skip equal values. Only dependent views are invalidated, and ordinary updates preserve local view state and retained nodes. Disposed mounts reject further updates. The handle bundle must implement Clone and be owned for the queued update ('static).
For a JavaScript host, expose an application-specific setter through wasm_bindgen and call it when host state changes. A React integration should keep input publishing separate from the mount effect, retain the latest inputs while WASM loads, and release the mount on cleanup.
Custom hosts and tests can call App::with_inputs(initialize) to receive (app, inputs), then publish changes with app.mutate(|rt| inputs.dark.set_if_changed(rt, dark)) and drive the normal host update cycle.
let mounted = refract_web::mount_with_inputs(
host_element,
refract_web::MountOptions::default(),
initialize,
)?;
// In the host's theme-change callback:
let dark = true;
mounted.update_inputs(move |inputs, rt| {
inputs.dark.set_if_changed(rt, dark);
})?;
// Keep mounted alive until the embedding app unmounts.Prerender with host inputs
Export the same initializer with export_prerender_with_inputs! and use hydrate_with_inputs in the browser. The macro accepts the same optional PrerenderOptions as export_prerender! and uses the existing refract build --release --prerender pipeline. Direct callers can use prerender_with_inputs(options, initialize).
Prerendering and hydration must use matching initial values. The snapshot contains HTML, not serialized input state; hydration recreates the state and event handlers. Keep initialization independent of browser APIs, and register side effects through the normal effect lifecycle. Publish the host’s latest values after hydration, then forward subsequent changes without remounting.
When a theme input defaults to light, a dark preference is applied after hydration. A dark-mode visitor may briefly see a light preview while WASM loads. If the first visible colors must match the host, use a matching themed snapshot or theme-aware CSS. Different initial trees follow the usual hydration fallback to a fresh mount.
// At module scope in the WASM entry module:
refract_web::export_prerender_with_inputs!(initialize);
// In the browser entry point, using the same initial values:
let mounted = refract_web::hydrate_with_inputs(
host_element,
refract_web::MountOptions::default(),
initialize,
)?;
// After hydration, publish the host's current preference.
mounted.update_inputs(move |inputs, rt| {
inputs.dark.set_if_changed(rt, host_dark);
})?;
// mounted.mount().hydrated() reports snapshot adoption.Render in a native window
The native adapter shares the graph, views, state, environment, and effects. It draws with a GPU renderer instead of embedding a browser. It does not turn controls into platform-native widgets.
use refract::prelude::*;
use refract_native::{NativeOptions, run};
fn main() -> refract_native::Result<()> {
run(
NativeOptions {
title: "Hello, Refract".into(),
..Default::default()
},
|_native| text("Hello from Rust").font_size(24.0),
)
}Read the host surface
Browser and native adapters install a shared Surface in the root environment before evaluating views. Retrieve it with cx.object::<Surface>()?. Each field is a separate read-only graph attribute: cx.read returns an owned value, and cx.with inspects it without cloning stored state. Reading the viewport does not subscribe a view to title or location changes.
The Surface internals guide explains ownership, request processing, and adapter integration.
| Field | Type | Meaning |
|---|---|---|
is_active | Read<bool> | Whether the native window or browser document is active. Logical element focus is retained while inactive; see Input & Focus. |
viewport | Read<Option<Viewport>> | Available layout space in logical pixels; None until the host measures it. |
title | Read<String> | Observed document title in the browser, or the title maintained by the native adapter. |
location | Read<Option<Url>> | Current application URL. Browser mounts read the document URL; native starts from NativeOptions::initial_url, which defaults to None. |
capabilities | Read<SurfaceCapabilities> | Whether this surface accepts title and navigation requests, through the title and navigation flags. |
Respond to available space
The browser measures the mount host’s content box, so embedded applications respond to their container rather than the whole browser window. Native measures the window’s inner size in logical pixels. Choose a fallback for the initial None measurement.
Use Derived::distinct when many viewport samples map to the same layout mode. For example, a derived width < 760.0 value only invalidates its consumers when that breakpoint changes. The chat example uses this to collapse its sidebar on smaller viewports.
| Viewport field | Type | Meaning |
|---|---|---|
width | f64 | Available width in logical pixels. |
height | Option<f64> | Some(height) for native windows and browser RootSizing::Fill; None for content-sized browser mounts, whose height is unconstrained. |
scale_factor | f64 | Physical pixels per logical pixel: browser device pixel ratio or native window scale factor. |
use refract::prelude::*;
#[view]
fn layout_mode(cx: &mut ViewContext<'_>) -> impl View {
let surface = cx.object::<Surface>()?;
let compact = cx.read(&surface.viewport)
.is_some_and(|viewport| viewport.width < 760.0);
text(if compact { "Compact layout" } else { "Wide layout" })
}Request title and history changes
Call surface.set_title(rt, title) or surface.navigate(rt, reference, mode) from an action or committed effect. Both return Result<Request, SurfaceError>. Successful admission queues host work; it does not mean the host has already applied the change. Keep the returned request when the UI needs to display its reactive status: Pending, Applied, or Failed(error).
HistoryMode::Push adds a history entry; Replace updates the current entry. Relative references resolve against the current application URL when executed, after earlier requests. With no current URL, supply an absolute URL. Navigation changes application location without loading another document or providing a router; application code decides how the URL maps to selected content.
Check surface.capabilities before enabling controls. Admission can fail with Unsupported, Full, or Closed. URL resolution and platform failures appear later in the request status. Browser navigation is subject to the browser’s same-origin history restrictions.
use refract::prelude::*;
// Call from an action using cx.runtime(), or from effect setup.
fn open_chat(rt: &mut Runtime, surface: &Surface) -> Result<Request, SurfaceError> {
surface.navigate(rt, "?chat=welcome", HistoryMode::Push)
}
fn rename_window(rt: &mut Runtime, surface: &Surface) -> Result<Request, SurfaceError> {
surface.set_title(rt, "Welcome — Chat")
}Do not enqueue requests while evaluating a view body or a derived computation. Read observations there; perform external work from actions or committed effects.
Opt into browser document control
MountOptions::default() observes the surface but sets both capability flags to false. Set manage_document: true for the mount that owns the document title and history. Only one controlling mount per document is allowed; additional observing mounts can coexist. Disposal releases document ownership.
Browser Back/Forward, hash changes, and external title changes are observed automatically. Refract history writes also notify other mounts. If an external router calls history.pushState or history.replaceState, call mounted.refresh_location() afterward to schedule a fresh observation; those browser methods do not emit popstate themselves.
let mounted = refract_web::mount(
host_element,
app_view,
refract_web::MountOptions {
manage_document: true,
sizing: refract_web::RootSizing::Fill,
..Default::default()
},
)?;RootSizing::Fill requires a host with a definite width and height. Keep mounted alive; use mounted.surface() to access its shared surface from host code.
Supply native application location
Native surfaces support title and navigation requests. set_title updates the window title. Navigation maintains in-memory application history; it does not open a browser, load a document, or persist history across launches.
Set NativeOptions::initial_url when starting the app. Host integrations can enqueue incoming URLs with NativeHandle::feed_location(url, mode) and traverse existing entries with NativeHandle::go(delta), such as go(-1) for Back. Incoming locations update the observable field without creating another outgoing navigation request. Wiring operating-system deep-link events is the host application’s responsibility.
NativeHandle::surface() returns the shared surface after app construction. It is not yet available inside the initial view factory; views should obtain it from the environment when their bodies run.
let options = refract_native::NativeOptions {
title: "Chat".into(),
initial_url: Some("app://chat/".parse().expect("valid application URL")),
..Default::default()
};Follow the update
An event changes graph state. The runtime evaluates affected mounted views and prepares semantic patches. The host applies those patches to retained elements, then the core commits the new baseline and runs effects.
The browser coalesces work into a microtask, with no permanent frame loop. Native apps reuse unchanged text shaping and layout. The default Vello renderer retains pixels between frames, repaints damaged regions, and skips rasterization for unchanged frames. It falls back to full rendering when required for correctness or when damage covers most of the target. See Native Rendering for damage tracking and full-render fallback conditions.
Know the current boundaries
Native support has been exercised on macOS. Native accessibility, virtualized lists, and general device-loss recovery remain future work. Channels deliver background results on web and native; Async Work explains the implementation.
Both adapters support content blur and backdrop blur. The browser uses CSS filters, while the default native Vello renderer uses GPU filtering and downsamples large surfaces or blur amounts to bound intermediate memory. Expect small rendering differences between hosts. See Blur and Backdrop Blur.
Platform services are injected into shared views. The portable graph and core have no browser, renderer, text-engine, or async-executor dependency. The native renderer can be replaced through run_with_renderer.