Islands
Brix renders Preact pages on the server and hydrates only components marked as islands, keeping static page content outside the browser interaction boundary.
Hydration attaches browser behavior to the HTML already on the page. A product description can stay server-only while its quantity picker becomes an island. Start with the smallest component that owns the interaction; a component with no event handlers or client state usually needs no directive. This guide applies to Brix's Preact applications, not managed React applications.
Create an island
#Generate the component and its browser test:
brix add island QuantityPicker --feature cart
This writes src/features/cart/QuantityPicker.tsx and QuantityPicker.client.test.tsx. Give the
component its interaction:
"use island";
import { useSignal } from "brix/hooks";
export function QuantityPicker() {
const quantity = useSignal(1);
return (
<button type="button" onClick={() => quantity.value++}>
Quantity: {quantity}
</button>
);
}
Render this component from a page and click it: the first response already contains Quantity: 1, then the browser updates the same button to Quantity: 2 without a navigation. That is the islands model: server-rendered content first, browser behavior only for the marked component.
An island module follows these rules, which discovery, brix doctor, and brix build enforce:
- The filename is PascalCase, such as
QuantityPicker.tsx. "use island"is the module's first statement. Comments may precede it, but the same string after an import is an ordinary expression and does not create an island.- The module has exactly one runtime export: a named PascalCase component. Type-only exports are allowed; default exports and other runtime exports fail.
- The component's name need not match the filename, and exporting a local alias such as
export { QuantityView as QuantityPicker }works. - The exported component must be created in the island module. Brix marks the exported component
itself, so an imported component would become this island everywhere it renders. Re-exports
(
export { QuantityPicker } from "./QuantityView.tsx"), imported bindings exported locally, and aliases of imports (export const QuantityPicker = QuantityView;) are rejected. Put the directive in the module that defines the component, or define a wrapper component as shown in Make a library component an island. - An island's identity is its source path without the extension, and Brix writes it into HTML
comments. File or directory names containing control characters,
&,",<, or>are rejected.
Import component hooks from brix/hooks, not directly from Preact or the signals package.
Make a library component an island
#A shared library's modules are outside the application's src/, so they cannot carry the
directive. Declare the island boundary in an application-owned wrapper that renders the library
component:
"use island";
import { DatePicker as LibraryDatePicker, type DatePickerProps } from "@acme/ui";
export function DatePicker(props: DatePickerProps) {
return <LibraryDatePicker {...props} />;
}
Render the wrapper where the page needs browser behavior. Other renders of the library component, including those inside the library's own components, stay server-rendered. Island props must still be serializable, so pass data rather than callbacks across the boundary.
If you add an invalid island while the development server is running, the terminal and browser error overlay identify the problem. Fix the file and save; discovery retries without a server restart and keeps its last valid catalogue until validation succeeds. Invalid modules are never renderable, and startup and production builds still reject them.
Render it from a page
#An ordinary server-rendered component can include the island normally:
import { QuantityPicker } from "#/features/cart/QuantityPicker.tsx";
export function ProductDetailsPage({ name }: { name: string }) {
return (
<main>
<h1>{name}</h1>
<QuantityPicker />
</main>
);
}
Brix server-renders the complete HTML, serializes the island's props, and hydrates the marked boundary in the browser. The page itself remains server-only.
Choose hydration timing
#The directive controls scheduling:
"use island"hydrates immediately."use island:idle"hydrates after immediate islands, one module at a time, yielding to the browser between modules."use island:lazy"hydrates each boundary when it comes within 200px of the viewport.
Any other suffix fails the build. Choose timing from actual interaction needs: keep important controls immediate and explicitly defer nonessential independent islands. Brix does not reorder islands by viewport position or business priority.
For example, a below-the-fold control can defer hydration:
"use island:lazy";
import { useSignal } from "brix/hooks";
export function ReviewFilters() {
const verifiedOnly = useSignal(false);
return (
<button
type="button"
aria-pressed={verifiedOnly.value}
onClick={() => (verifiedOnly.value = !verifiedOnly.value)}
>
{verifiedOnly.value ? "Showing verified reviews" : "Showing all reviews"}
</button>
);
}
The example toggles filter state; use that state when rendering your review list or calling its API.
Lazy defers hydration work, not the download. Brix starts importing every idle and lazy module
as soon as immediate islands have hydrated, then waits for visibility before hydrating each lazy
boundary. A lazy boundary hydrates without waiting when the browser lacks IntersectionObserver or
when the island renders no element to observe (for example, text only).
Brix observes every top-level element the island renders, so a leading style element, JSON-LD
script element, or hidden element does not stop visible content from triggering hydration. When none
of the island's elements has a layout box, such as a control rendered hidden until hydration
reveals it, Brix observes the nearest enclosing element that is not display: contents instead.
Inside a hidden container, the boundary waits until that container is shown and nears the viewport.
How the schedule runs:
- Immediate modules within each page or fragment root download concurrently, then hydrate in
document order in short, time-bounded batches. Brix checks its budget between modules, yielding
through
scheduler.yield()or a timer; it does not interrupt a single large island or a module's repeated instances mid-hydration. - Idle work yields through
scheduler.yield()when available, otherwise an idle callback or timer. - If one instance of a module fails to hydrate, Brix still hydrates the module's other instances and
reports the failures together afterwards. This includes an instance whose end marker the HTML
parser moved, such as island rows rendered directly inside
<table>without a<tbody>. A failed module download affects every boundary of that module. - Independent fragment roots initialize concurrently; nested roots initialize ancestor first, and the generated bootstrap initializes fragments before page islands.
- Lazy discovery stays within its page or fragment root. Reusing a lazy island in nested fragments does not share their props or render data: each boundary hydrates with its owning root's payload.
Discovery scans each page or fragment root once for the boundaries of every island module, and scans a newly attached slot once for the modules registered so far. Wide static lists do not overflow the JavaScript call stack. Large DOM trees still cost a traversal and rendering time; this is not list virtualization.
Pass props
#Props cross a serialization boundary from server to browser. Island props support JSON values plus
undefined, NaN, Infinity, -0, Date, RegExp, URL, Map, Set, BigInt, and typed
arrays such as Uint8Array. Shared references and cycles across plain objects, arrays, Maps, and Sets are preserved,
so an object passed separately as a prop remains usable as a Map key or Set member.
- Functions fail with an error naming the island and the prop path, such as
order.onSelect. Move the callback inside the island, or let an outer island own the component. A render-propchildrenfunction fails the same way. - Arbitrary class instances, request contexts, and services cannot be serialized; the error names the island and the prop path. Pass the data they hold instead.
- A signal prop is serialized by its current value and revived as a new, independent signal in the
browser. Each island and each slot remount gets its own signal, even when the server passed the
same signal to several islands. This includes signals nested in another signal's value, such as
signal([{ done: signal(false) }]), and acomputedprop, which is revived as a computed fixed at its server value. To share reactive state between islands, use a store or a module-level shared signal. - Other prop values are revived once per page and shared by reference between islands and remounts that received the same server value. Treat props as read-only rather than mutating them.
- JSX values become server-rendered slots; see slots.
All serialized props are visible in the page's HTML. Never pass credentials or other secrets.
Understand nested islands
#When one island renders another island normally, the outer island owns that interactive subtree. Brix emits and hydrates only the outer boundary; the inner directive does not create a second hydration boundary.
An island passed through server-owned JSX slot content remains independent. Prefer straightforward composition and avoid wrappers created only to force another boundary.
Pass server-rendered content through slots
#Pass JSX as children, a named prop, or inside plain objects, arrays, Maps, and Sets. Brix preserves that content as server-rendered HTML rather than shipping the server component to the browser:
<PriceDialog priceTable={<PriceTable prices={prices} />} />
The island can render priceTable inside a client-only portal. This works when the dialog starts closed, with or without keepMounted. Brix renders content skipped during SSR once into inert fallback templates, retaining the island's ancestor server context. Ordinary rendered slots do not get duplicate fallback content. Nested slots, islands, styles, and translation dependencies are discovered before the response is finalized.
Closed slots still cost server work and response bytes. Their content is eagerly prepared and included in the initial HTML and hydration payloads, even when no dialog is visible. Reopening restores that snapshot; it does not rerun server loaders. If data should load only after interaction or must be refreshed, fetch it through an authorized API route from the island instead of putting it in a hidden slot.
Hiding content is not authorization. Authorize access in the application before rendering the
slot, and never include secrets in its HTML or serialized props. For sensitive personalized
responses that must not be stored, set Cache-Control: private, no-store in server middleware.
Route cache: false is only an edge-cache hint; it does not set HTTP no-store. Assess page-shell
and fragment cache partitions independently: a private fragment does not make a personalized
shell safe to share. Public content can still use an appropriate shared cache policy; see
fragment cache ownership.
Contentful adapters reached in these hidden server-authored slots run their server loaders during slot preparation. The browser attaches that HTML without rerunning server-only adapters. Independent islands inside the slot retain their client-consumed results; server-only slot results are excluded unless independently reachable from client data. This differs from constructing a loader-backed adapter for the first time in response to browser state: loaders without explicit client-loading authorization require an SSR-prepared result and otherwise fail before calling the component. Authorized adapters can instead render pending and load through the framework endpoint; see client-introduced adapters. Use a server-authored slot for content known at render time.
Static-only slots preserve their DOM shape, including table rows and options. Remounting one
restores cloned server nodes with their attributes copied verbatim; Brix does not serialize and
reparse the HTML or reinterpret attributes such as draggable="false" as component props.
Slots that contain an island, a script, a template, or a shadow root are attached through a
<brix-slot style="display:contents"> wrapper. display: contents keeps the wrapper out of layout,
but it is still an element in the DOM: child combinators such as .list > li, :first-child and
:nth-child selectors, and parents that accept only specific children (<table>, <ul>,
<select>) see it. Style the slot content itself, and keep constrained structures entirely inside
the slot content rather than split between the island and the slot.
For interaction inside a slot, include an island. It hydrates once its DOM is attached and its
module is available, even if that module arrives after the dialog opens. Hidden keepMounted
content counts as attached. Ordinary lazy boundaries still wait for viewport visibility; restored
slot boundaries activate on attachment and module arrival.
Unmounting a slot cleans up its nested islands, including effect subscriptions and timers. Reopening restores the original server HTML and creates fresh local component state, including signal props revived from their server values, like remounting an ordinary Preact subtree. Shared external stores persist. Server-only components do not rerun on reopening.
Hiding content with keepMounted or moving its DOM into a portal does not unmount it: local state and effects remain active. If a hidden dialog should pause an effect, coordinate visibility explicitly. Modules arriving after a slot has unmounted cannot activate that disposed instance; a reopened slot gets a fresh instance instead.
Slot HTML does not make server callbacks or arbitrary server components executable in the browser. Preserve fallback templates when transforming HTML or composing fragments. If slot HTML is missing, hydration reports the prop name and slot ID; check that server and browser assets use the same Brix build and that HTML processing retained the templates.
Read shared render data
#Use useRenderData from brix/hooks to read the nearest Brix render-data provider during SSR and page or fragment island hydration. Brix supplies the provider automatically; do not copy its data into a store or create an application context bridge.
Share a browser-safe type between the server callback and islands:
import type { BaseRenderData } from "brix/islands";
export interface AppRenderData extends BaseRenderData {
role: "reader" | "editor";
}
Give the server's renderData callback an explicit AppRenderData return type and preserve ...defaults. Populate the role from server-validated application identity; it is only a display hint in the browser. See server render data.
"use island";
import { useRenderData } from "brix/hooks";
import type { AppRenderData } from "#/render-data.ts";
export function RoleLabel() {
const { role } = useRenderData<AppRenderData>();
return <span>{role}</span>;
}
BaseRenderData supplies baseUrl, urlPath, initialQueryParams, locale (the finalized
request locale), nonce, isProduction, and version. The CSP nonce is available during SSR
only: Brix never serializes it, and browser renders observe an empty string.
Without a type argument, the hook returns Readonly<BaseRenderData>. The custom type describes the serialized data; it does not add fields or perform runtime validation. Readonly is shallow and compile-time only. Render data is distinct from server request context and mutable stores; use signals or stores for interactive state. Page and fragment roots read their own provider values, and replacing a wrapper's renderData updates its readers.
The hook throws outside a provider. In isolated tests or Storybook stories, wrap the component with RenderDataWrapper from brix/islands and supply a complete renderData fixture. Do not reset browser-global registries between renders. Browser path/query values reflect the wrapper's live location when rendered; the hook is not a navigation subscription.
All render data is browser-visible. Never include credentials, and never authorize server operations using a client-reported role. Browser-safe data is not necessarily safe to place in a public cache: partition or disable page and fragment caching for personalized fields. Managed React applications do not use Brix islands and have no corresponding render-data hook.
Deploy matching server and browser artifacts together. When a Brix upgrade changes the hydration format, invalidate cached page and fragment HTML produced by the previous version.
Keep boundaries safe
#Island modules are browser code. Do not import #brix/server, brix/server, environment secrets, databases, or other server-only modules. Move data loading into a page route or call a typed API route.
Islands also render on the server, so read browser globals such as window, document, or
localStorage in effects or event handlers rather than during render. When shared code must branch,
getWindow() from brix/islands returns window in the browser and null on the server. Keep
the server and first browser render identical to avoid hydration mismatches.
When a browser import reaches a module marked "use server", development and production builds
fail with the available importer ancestry, including workspace libraries and re-exports:
Server-only module imported in client bundle: ../data/src/credentials.ts
Import chain (available browser graph):
src/features/search/Search.tsx
→ ../data/src/index.ts
→ ../data/src/credentials.ts
Follow the chain to the shared entry point. Split browser-safe contracts and types from server
implementations; use explicit import type or export type for type-only dependencies. The guard
runs before final tree shaking, so an unused server re-export in a mixed barrel can still fail.
The trace includes only ancestry available when the error occurs, not necessarily the entire path
from an entry point. "use server" marks a whole module; it does not generate RPC calls. Server
imports remain valid during SSR.
The boundary is checked before Brix and other source transforms, against each file on disk, and
during development dependency optimization, including transitive installed-package imports. It
also covers production Web Worker bundles (new Worker(new URL(...)), ?worker, ?sharedworker),
query imports that would publish source text (?raw, ?url, ?inline, including
import.meta.glob queries), and asset URLs created with new URL("./file", import.meta.url). Optimization failures name the
server-only dependency in the terminal; the browser may show a dependency-loading error rather
than that full diagnostic. Split the dependency's browser/server entry points instead of bypassing
the guard. Unmarked modules and embedded secret values are not detected automatically.
Brix fails the render of a page or fragment, with or without islands of its own, whose HTML
(including <Head> content) contains island boundary markup it did not emit, for example
<!--brix:island:...--> copied into a CMS string rendered with dangerouslySetInnerHTML. Every
form a browser parses as a comment counts, including <!brix:...> and comments closed with --!>.
Raw HTML must also not contain data-brix-fragment or data-brix-fragment-hydration attributes: fragment roots and their
metadata are added around rendered output, so raw markup imitating them would let the page bootstrap
hydrate a real island module with props the markup supplies. Remove such markup from raw HTML.
Ordinary comments, and a stray <!-- inside raw script content or an attribute value, do not affect
boundary detection, and Brix text or attribute values that merely mention these names are accepted.
Fragment roots hydrate only when their metadata is a server-shaped JSON script and their island
modules load from the application's asset prefix; see
fragment islands and CSP.
Write Preact components
#Brix applications use Preact 11 through Brix-owned import paths. Do not install Preact or its signals package directly.
brix/preactre-exports Preact, including DOM types such asCSSPropertiesandTargetedEvent. Import those directly rather than through theJSXnamespace.brix/hooksis the single import path for Preact hooks, includinguseLayoutEffect,useReducer,useContext,useId,useSignal,useComputed, and the Brix hooks.brix/signalsexports signal primitives for module code:signal,computed,effect,batch,untracked,action,createModel, and theSignalclass. Component hooks are not repeated there.brix/preact/compatexposes onlycreateElement,forwardRef, and theComponentProps,ComponentType, andJSXtypes, for components that need those compatibility APIs.
Preact 11 initializes useRef explicitly (include null in nullable ref types), passes ref to
function components as a prop, and compares hook values with Object.is. Use explicit units for
inline dimensions and default parameter values instead of defaultProps. useEffect cleanup on
unmount runs after paint; use useLayoutEffect when cleanup must run synchronously, and flush
effects in tests before asserting cleanup. When upgrading an existing project, follow the
framework migration steps.
Verify interaction
#If HTML appears but controls do nothing, confirm that the component is inside a hydrated island,
then inspect the browser console and network panel for missing modules or CSP failures. Hydration
failures are always logged. Run brix doctor and brix build to catch discovery and server-import
errors, and keep server and browser files from the same build.
For timing diagnostics, run localStorage.setItem("brix:debug", "1") in the browser console and
reload. Brix then logs each island's module-fetch and hydration time and a completion summary.
Remove the key when finished.
Use browser component tests for event handling and route harness tests for server rendering:
brix test --project browser
brix test --project node
brix build
See testing for the distinction between browser tests, route tests, and HTTP contract mocks. Component tests do not exercise separate production island bundles; use an application E2E test for that boundary.
Low-level hydration entry point
#Brix's generated client entry and island manifest start hydration; ordinary applications never
call it themselves. Deliberate framework integrations can use init(islands, config, root?) from
brix/islands/client, which takes already-resolved island URLs and priorities. It fetches
immediate modules concurrently, hydrates them before resolving, then only schedules idle and lazy
work. Scheduling lasts for the page's lifetime; there is no disposal API. Passing a fragment root
scopes hydration to that root and does not publish document completion.
InitConfig.onIslandHydrated, onIslandError, and onHydrationComplete are synchronous
diagnostic observers. In onIslandHydrated metrics, fetchTime runs from the module request until
it settles and hydrateTime covers hydration only; waiting for idle time or visibility counts
toward neither. A thrown observer exception is logged separately; it does not stop other
islands, is never sent to onIslandError, and does not turn successful hydration into a failure.
Genuine import and render failures still log and reach onIslandError, which receives an
AggregateError when several instances of one module fail. Brix does not await observers, so
handle asynchronous rejections inside your callback. Document completion follows immediate and
idle work, does not wait for lazy islands, and does not mean every island succeeded. Do not use
these callbacks to orchestrate application behavior.