Build managed React applications
Create and operate a browser-only managed React SPA or Contentful App with Brix-owned runtime and Vite integration.
Create a managed React SPA
#Create a standalone app:
brix create react-app customer-portal
cd customer-portal
brix dev
Open the local URL that brix dev prints to see the client-rendered starter counter. Edit
src/App.tsx to change that screen; there is no Brix server route or SSR process behind it.
From a Brix workspace root, omit --version; the new member uses the workspace's exact Brix version, and a bare name is placed under apps/:
brix create react-app customer-portal
brix doctor#customer-portal
brix dev#customer-portal
The generated manifest declares brix.project: "react-application". It has a root index.html, src/main.tsx, src/App.tsx, src/brix.ts, and this Vite configuration:
import { defineBrixReactConfig } from "@brix/react/vite";
export default defineBrixReactConfig();
defineBrixReactConfig configures the managed React JSX runtime, deduplicates React and ReactDOM, supplies browser-safe aliases, and adds the Brix Vitest configuration. Its optional vite value accepts the supported Brix Vite escape hatch as an object or a function of the Vite environment:
export default defineBrixReactConfig({
vite: ({ mode }) => ({
base: mode === "production" ? "/portal/" : "/",
define: { __APP_VARIANT__: JSON.stringify(mode) },
}),
});
The escape hatch is an allowlist. For a browser-only application the useful options are base,
build.minify, build.sourcemap, define, plugins, publicDir, resolve, and server. Brix
rejects unsupported options such as root, appType, envDir, esbuild, oxc, other build
keys, and resolve.jsxImportSource, as well as plugins whose names start with brix:. Unlike full-stack
applications, which use assetPrefix, a React application sets its deployed path with base.
Like full-stack applications, managed React builds disable Vite dotenv discovery (envDir: false),
so root .env files never reach the browser bundle. Anything you put in define is public.
React applications have no Brix environment integration: brix env and the lifecycle --env and
--stage options require a full-stack application and fail in a React project. Select public
per-mode values, such as the API origin, in the Vite configuration instead:
import { defineBrixReactConfig } from "@brix/react/vite";
const apiOrigins: Record<string, string> = {
development: "http://localhost:3000",
staging: "https://api.staging.example.com",
production: "https://api.example.com",
};
export default defineBrixReactConfig({
vite: ({ mode }) => ({
define: { __API_ORIGIN__: JSON.stringify(apiOrigins[mode] ?? apiOrigins.production) },
}),
});
Declare the constant for TypeScript in a source declaration file such as src/globals.d.ts
(declare const __API_ORIGIN__: string;), pass it as baseUrl, and select the mode with
brix build --mode staging. Never define credentials or other secrets this way.
Use the managed runtime
#Import React APIs and types from @brix/react, not directly from react. Mount through the client entry point; react-dom root APIs come from @brix/react/dom. brix doctor and brix check reject direct react and react-dom imports, including type-only imports:
import { StrictMode } from "@brix/react";
import { createRoot } from "@brix/react/client";
import { App } from "./App.tsx";
const element = document.getElementById("root");
if (!element) throw new Error("React application root is missing");
createRoot(element).render(
<StrictMode>
<App />
</StrictMode>,
);
The root adapter also exports Brix's React bindings:
useApifor contract-aware requestsuseSignal,useComputed, anduseSignalsfor React signal integrationuseStorage,useLocalStorage, anduseSessionStorageTranslationProviderandcreateTranslationHookssignal,computed,effect,batch,untracked,action,createModel,useSignalEffect, and theSignal/ReadonlySignaltypes for shared signal state- the supported React runtime, hooks, elements, and component types, plus every element attribute
(
InputHTMLAttributes,SVGProps, ...), synthetic event (PointerEvent, ...), and event handler (MouseEventHandler, ...) type
For another React type, derive it from an exported one, such as ComponentProps<"input"> or
JSX.IntrinsicElements["dialog"].
@brix/react/dom provides the browser-relevant react-dom root API: createPortal, flushSync,
useFormStatus, requestFormReset, and the preconnect, prefetchDNS, preinit,
preinitModule, preload, and preloadModule resource hints:
import type { ReactNode } from "@brix/react";
import { createPortal } from "@brix/react/dom";
export function Dialog({ children }: { children: ReactNode }) {
return createPortal(<div role="dialog">{children}</div>, document.body);
}
useSignal stores its signal in React state, so Fast Refresh keeps local signal values and useApi
data while you edit a compatible component. Call useSignals() in a component that reads signal .value during render. This explicitly tracks
those reads and re-renders the component when they change. A signal passed directly as a React child
is reactive without useSignals():
import { useComputed, useSignal, useSignals } from "@brix/react";
export function Counter() {
useSignals();
const count = useSignal(1);
const doubled = useComputed(() => count.value * 2);
return (
<button onClick={() => count.value++}>
{count.value}/{doubled.value}
</button>
);
}
Create shared state outside components with signal and computed from @brix/react. Every
component that reads the state's .value during render calls useSignals():
import { computed, signal } from "@brix/react";
export const cartItems = signal<string[]>([]);
export const cartCount = computed(() => cartItems.value.length);
import { useSignals } from "@brix/react";
import { cartCount } from "./cart.ts";
export function CartBadge() {
useSignals();
return <span>{cartCount.value}</span>;
}
Module-level signals live for the page session and are shared by every component that imports them; reset them explicitly where needed, for example on logout.
Define browser-safe contracts with defineBrix in src/brix.ts:
import { defineBrix } from "brix/contracts";
export const brix = defineBrix();
export const { createApiContract, executeApi, getPath } = brix;
For a standalone example, define a local browser-safe contract using that project binding. The separately deployed API must implement the same path and response:
import { createApiContract } from "#brix";
import { z } from "brix/zod";
export const productApiContract = createApiContract({
method: "GET",
path: "/api/products/:productId",
response: z.object({ id: z.string(), name: z.string() }),
});
Combine the contract with the React hook in the same directory:
import { useApi } from "@brix/react";
import { productApiContract } from "./contract.ts";
export function Product({ productId }: { productId: string }) {
const request = useApi(productApiContract, {
baseUrl: "https://api.example.com",
});
if (request.isLoading.value) return <p>Loading…</p>;
if (request.isError.value) return <p>Request failed: {request.error.value?.message}</p>;
if (request.data.value) return <h1>{request.data.value.name}</h1>;
return (
<button onClick={() => void request.execute({ params: { productId } })}>Load product</button>
);
}
Replace https://api.example.com with the actual API origin. In a workspace, prefer exporting this
contract from a browser-safe library and linking that library to both consumers instead of copying
it. Consult API routes for request options and shared contracts.
Unlike a component that reads a standalone signal, this example does not need its own useSignals():
the React useApi binding establishes tracking internally. execute is explicit here; the request
does not run merely because the component mounted or productId changed.
Each execute callback captures its render's contract and options, so a suspended transition cannot
redirect requests from the committed UI. Changing the contract or options object changes execute
and the hook result object's identity. Inline options therefore produce a new callback each render;
memoize options when using execute as an effect dependency to avoid a request loop. Retained old
callbacks and cache refreshes keep their original configuration and success/error callbacks; call
the current execute to adopt replacements. New callbacks work immediately in child layout effects,
without waiting for a parent effect to publish configuration.
When an Activity becomes hidden, useApi releases its request and cache observation. Data and
completed errors remain; interrupted loading becomes idle without data or success with retained
data, and both fetching flags become false. Revealing does not fetch or reconnect the cache observer:
call execute() to resume. Until then, retained data may be stale, including after cache invalidation.
Other callers sharing cached work continue; cancelled work cannot update this hook or its callbacks.
TranslationProvider receives the complete dictionary used for the active locale. It does not load or
merge the translation definition's fallback locale. If a React application needs fallback messages,
merge its fallback dictionary behind the active dictionary before passing dictionary; missing keys
otherwise use onMissing, then the supplied example or key according to the normal translator rules.
Without onMissing, development browsers warn once per locale and key, matching the Preact provider;
production builds stay silent.
Understand the application boundary
#A managed React application builds once to dist. It is not a Brix server application and has:
- no Hono API or page route implementation
- no SSR,
createBrixApp, or Nodestartcommand - no Preact islands or hydration directives
- no Panda integration; use the React application's chosen CSS approach
- no managed Brix Storybook support
The managed browser graph rejects modules marked with a top-level "use server" directive,
including transitive imports, re-exports from shared libraries, Web Worker bundles, and source
published through ?raw/?url imports or new URL(..., import.meta.url) assets. Keep contracts and utilities
imported by React browser code browser-safe; move server-only implementations behind the separately
deployed API. This guard is not a secret detector: unmarked modules and embedded values are still
your responsibility.
Call a separately deployed Brix API
#Shared contracts let the React browser call a separately deployed Brix application (a BFF); they do
not make the deployments same-origin. Pass the BFF's deployed origin as baseUrl, then allow the
SPA's exact origin on the BFF in two places:
- CORS lets the browser read responses. Add
cors()frombrix/hono/corsto the server'smiddleware. - Cross-origin write protection rejects browser requests from other origins, including sibling subdomains, with 403 for every method except
GET,HEAD, andOPTIONS, even when CORS allows them. List the SPA origin incsrf.trustedOrigins; otherwise the 403 also lacks CORS headers and the browser reports a CORS error.
In the BFF application's server setup:
"use server";
import { cors } from "brix/hono/cors";
import { defineBrixServer } from "brix/server";
import { brix } from "./brix.ts";
import { env } from "./env.server.ts";
const portalOrigin = "https://portal.example.com";
export const brixServer = defineBrixServer(brix, {
env,
csrf: { trustedOrigins: [portalOrigin] },
middleware: [cors({ origin: portalOrigin })],
});
export const {
createApiRoute,
createFragment,
createMarkdownIndexRoute,
createPageRoute,
createResponseRoute,
} = brixServer;
Trusted origins are exact http(s)://host[:port] values without paths or wildcards. A local SPA dev
server on another port is a different origin, so add it only to the development configuration, for
example from a non-sensitive environment value. See
cross-origin browser calls, workspaces, and the
caching guide.
Verify and publish the browser bundle
#brix doctor
brix check
brix test
brix build
Managed React config supplies Node, browser, and typecheck test projects. Each project receives the
React aliases, React/ReactDOM deduplication, and your vite.define/vite.resolve values; browser
*.client.test.tsx files compile with the managed JSX runtime and may import brix/test. Render
components with @brix/react/test, which also exports Vitest's page and userEvent:
// src/App.client.test.tsx
import { expect, it } from "brix/test";
import { render, userEvent } from "@brix/react/test";
import { App } from "./App.tsx";
it("counts clicks", async () => {
const screen = render(<App />);
await userEvent.click(screen.getByRole("button", { name: "Count: 0" }));
await expect.element(screen.getByRole("button", { name: "Count: 1" })).toBeVisible();
});
render mounts inside React's act environment, accepts a wrapper provider component, and cleans
up earlier trees before each test. brix/test/browser is Preact-only, so doctor rejects it in a
React application, and managed Node tests cannot import @brix/react/test. Use
managed E2E for behavior across the built application. A test command with no
matching tests can pass, so confirm that your intended cases were collected.
Deploy the complete dist/ directory to a static host. There is no Node server to start. Configure
the host's asset paths to match vite.base; if you add client-side routing, configure its document
fallback deliberately and test a direct visit to a nested URL. Set document security headers on this
host, not only on the BFF. Any value embedded in this bundle is public—never put server credentials
in Vite defines, browser configuration, or shared contracts.
Create a Contentful App
#Use the dedicated preset rather than adding Contentful packages by hand:
brix create contentful-app editorial-tools
Run the same command at a workspace root to add it as a member; as with react-app, a bare name is
placed under apps/.
This remains a react-application, but records the Contentful integration and adds exact compatible SDK, Forma 36, icon, and app-script dependencies. The generated Vite config uses a relative base required by uploaded Contentful assets:
import { defineBrixReactConfig } from "@brix/react/vite";
export default defineBrixReactConfig({ vite: { base: "./" } });
Import the managed surfaces through Brix:
import { useEffect } from "@brix/react";
import { Button, GlobalStyles, Heading } from "@brix/react/contentful";
import { PlusIcon } from "@brix/react/contentful/icons";
import { init, type KnownAppSDK } from "brix/contentful/app";
The generated entry calls init, renders with its SDK, and handles the app configuration location. Preserve base: "./"; brix doctor reports drift. Continue with the Contentful guide.
To add Brix bindings to a React application that keeps its own build, continue with integrate an external React host.