Part 6: Build the UI with Effect UI
Build a browser app with Effect UI: sign in, open your account, deposit, and see the balance change as it happens. Effect UI tests a component the way the domain tests a model: as a story of messages in and effects out.
Install
Section titled “Install”pnpm add effect@~4.2.0 @effect/platform-browserpnpm add -D vite https://pkg.alchemy.run/@alchemy.run/frontend-frameworks/489dac8bun add effect@~4.2.0 @effect/platform-browserbun add -d vite https://pkg.alchemy.run/@alchemy.run/frontend-frameworks/489dac8npm install effect@~4.2.0 @effect/platform-browsernpm install -D vite https://pkg.alchemy.run/@alchemy.run/frontend-frameworks/489dac8yarn add effect@~4.2.0 @effect/platform-browseryarn add -D vite https://pkg.alchemy.run/@alchemy.run/frontend-frameworks/489dac8Effect UI ships in effect from 4.2, under effect/ui. @alchemy.run/frontend-frameworks builds the app with Vite when you deploy it.
Add the browser’s types
Section titled “Add the browser’s types”The app runs in a browser. Add "DOM" to lib in your tsconfig.json, so document and location type-check:
{ "compilerOptions": { "lib": ["ESNext", "DOM"] }}Configure Vite
Section titled “Configure Vite”import { defineConfig } from "vite";
export default defineConfig({ optimizeDeps: { entries: ["src/web/entry.ts"], include: ["effect", "effect/Function", "effect/http", "effect/ui", "effect/ui/html"], },});The app runs in the browser alone, so it needs no Vite plugin. include pre-bundles the Effect modules, so the browser loads one copy of Effect.
Add the page
Section titled “Add the page”<!doctype html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Bank</title> </head> <body> <div id="root"></div> <script type="module" src="/src/web/entry.ts"></script> </body></html>Read the session cookie
Section titled “Read the session cookie”import * as Effect from "effect/Effect";import * as Cookies from "effect/http/Cookies";import * as Headers from "effect/http/Headers";import * as Layer from "effect/Layer";// ...) {}
// Demo only: trusts `Authorization: Bearer <customer id>`. Verify a real session in production.export const SESSION_COOKIE = "bank_session";
// The customer from the session cookie (browsers), or the Authorization header (scripts).const signedIn = (headers: Headers.Headers): Option.Option<string> => Option.orElse( Option.flatMap(Headers.get(headers, "cookie"), (cookie) => Option.fromNullishOr(Cookies.parseHeader(cookie)[SESSION_COOKIE]), ), () => Option.flatMap(Headers.get(headers, "authorization"), (value) => value.startsWith("Bearer ") ? Option.some(value.slice("Bearer ".length)) : Option.none(), ), );
// Demo only: trusts the cookie or header as given. Verify a real session in production.export const SessionLive = Layer.succeed(Session, (effect, { headers }) => Option.match(Headers.get(headers, "authorization"), { Option.match(signedIn(headers), { onNone: () => Effect.fail(new Unauthorized()), onSome: (value) => value.startsWith("Bearer ") ? Effect.provideService(effect, CurrentActor, { customerId: CustomerId.make(value.slice("Bearer ".length)), }) : Effect.fail(new Unauthorized()), onSome: (customerId) => Effect.provideService(effect, CurrentActor, { customerId: CustomerId.make(customerId) }), }),);A browser can’t set headers on a WebSocket, but it always sends its cookies. Session now reads the customer from the bank_session cookie, and falls back to the header for scripts.
Sign in
Section titled “Sign in”import * as Cookies from "effect/http/Cookies";import * as Headers from "effect/http/Headers";import { HttpServerRequest } from "effect/http/HttpServerRequest";import * as HttpServerResponse from "effect/http/HttpServerResponse";import * as Layer from "effect/Layer";import * as Option from "effect/Option";// ...);
// POST /api/session signs a customer in. Demo only: anyone may sign in as anyone.export const sessionRoute = Effect.gen(function* () { const request = yield* HttpServerRequest; const body = yield* request.json.pipe( Effect.flatMap(Schema.decodeUnknownEffect(Schema.Struct({ customerId: CustomerId }))), Effect.option, ); if (Option.isNone(body)) return HttpServerResponse.text("Expected { customerId }", { status: 400 }); return HttpServerResponse.empty({ status: 204 }).pipe( HttpServerResponse.setCookieUnsafe(SESSION_COOKIE, body.value.customerId, { httpOnly: true, secure: true, sameSite: "strict", path: "/", }), );});
export const sessionClient = (customerId: string) => RpcMiddleware.layerClient(Session, ({ request, next }) =>sessionRoute sets the cookie. HttpOnly keeps it out of reach of scripts, and SameSite=Strict keeps it off requests from other sites.
Route sign-in
Section titled “Route sign-in”import * as DomainCloudflare from "@alchemy.run/domain/Cloudflare";import * as Effect from "effect/Effect";import { HttpServerRequest } from "effect/http/HttpServerRequest";import * as Layer from "effect/Layer";import { Bank, BankHandlers } from "./Bank.model.ts";import { BankApi } from "./BankApi.api.ts";import { SessionLive } from "./Session.middleware.ts";import { SessionLive, sessionRoute } from "./Session.middleware.ts";
const BankLive = SessionLive.pipe( // ... Effect.gen(function* () { const api = yield* BankApi; return { fetch: api.fetch }; return { fetch: Effect.gen(function* () { const request = yield* HttpServerRequest; const path = new URL(request.url, "http://localhost").pathname; return path === "/api/session" ? yield* sessionRoute : yield* api.fetch; }), }; }).pipe(Effect.provide(BankLive)),) {}/api/session signs in, and everything else goes to the Api.
Derive the bank’s commands and view
Section titled “Derive the bank’s commands and view”import * as DomainEffectUI from "@alchemy.run/domain/EffectUI";import { BankApi } from "../BankApi.api.ts";
// The bank's commands and its view, as Effect UI services.export const BankUI = DomainEffectUI.make(BankApi);BankUI has one Effect UI Command per Api command and one query per view. BankUI.layer runs them on the bank client, which the app provides when it starts.
Name what can happen
Section titled “Name what can happen”import * as DomainEffectUI from "@alchemy.run/domain/EffectUI";import { UiSchema } from "effect/ui";import * as Schema from "effect/Schema";import { BankApi } from "../BankApi.api.ts";// ...export const BankUI = DomainEffectUI.make(BankApi);
export const BankMessage = UiSchema.TaggedEnum({ ClickedOpen: {}, ClickedDeposit: {}, Succeeded: {}, Failed: { reason: Schema.String },});A message is everything that can happen to the app: a click, or the answer to a command.
Send domain commands
Section titled “Send domain commands”import * as DomainEffectUI from "@alchemy.run/domain/EffectUI";import { UiSchema } from "effect/ui";import { Command, UiSchema } from "effect/ui";import { Html } from "effect/ui/html";import * as Schema from "effect/Schema";import { AccountId } from "../Account.id.ts";import { BankApi } from "../BankApi.api.ts";import { CustomerId } from "../Customer.id.ts";// ... Failed: { reason: Schema.String },});
const accountIdOf = (customerId: typeof CustomerId.Type) => AccountId.make(`${customerId}-main`);
export const BankNoDeps = Html.component({ name: "Bank", props: Schema.Struct({ customerId: CustomerId }), model: Schema.Struct({ error: Schema.NullOr(Schema.String) }), message: BankMessage,}).make({ init: () => ({ error: null }), update: { ClickedOpen: ($) => $.run( BankUI.RegisterCustomer.make({ input: { customerId: $.props.customerId, name: $.props.customerId }, }).pipe( Command.match({ onSuccess: () => BankMessage.Succeeded(), onFailure: (failure) => BankMessage.Failed({ reason: failure._tag }), }), ), ), ClickedDeposit: ($) => $.run( BankUI.DepositMoney.make({ input: { accountId: accountIdOf($.props.customerId), amount: 1_000 }, }).pipe( Command.match({ onSuccess: () => BankMessage.Succeeded(), onFailure: (failure) => BankMessage.Failed({ reason: failure._tag }), }), ), ), // The balance arrives through the view; success only clears an error. Succeeded: ($) => $.evolve({ error: null }), Failed: ($, { reason }) => $.evolve({ error: reason }), },});The signed-in customer is the component’s props. A click runs a domain command and maps its outcome to a message: a rejection, a refused session or a lost reply becomes Failed with its tag. The balance never changes on success: it comes from the bank, through the next step.
Read the balance
Section titled “Read the balance” model: Schema.Struct({ error: Schema.NullOr(Schema.String) }), message: BankMessage, queries: { summary: { query: BankUI.AccountSummary, args: ({ props }) => ({ key: accountIdOf(props.customerId) }), }, },}).make({The AccountSummary view is a query keyed by the account. The bank pushes every change over a WebSocket, so a deposit from any device shows up here.
Draw the page
Section titled “Draw the page”import * as DomainEffectUI from "@alchemy.run/domain/EffectUI";import { Command, UiSchema } from "effect/ui";import { Command, Component, UiSchema } from "effect/ui";import { Html } from "effect/ui/html";import * as Option from "effect/Option";import * as AsyncResult from "effect/reactivity/AsyncResult";import * as Schema from "effect/Schema";// ... Failed: ($, { reason }) => $.evolve({ error: reason }), }, view: (h, model) => { const summary = Option.flatMap(AsyncResult.value(h.queries.summary), ({ state }) => state); const balance = Option.flatMap(summary, ({ owner, balance }) => owner === null ? Option.none() : Option.some(balance), ); return h.div( h.p(`Signed in as ${h.props.customerId}`), Option.match(balance, { onNone: () => h.button.on("click", BankMessage.ClickedOpen()).children("Open my account"), onSome: (balance) => h.div( h.p.attr("aria-label", "Balance").children(`Balance: ${(balance / 100).toFixed(2)}`), h.button.on("click", BankMessage.ClickedDeposit()).children("Deposit 10.00"), ), }), model.error !== null && h.p.attr("role", "alert").children(model.error), ); },});
// The app with its commands and view provided; the entry provides the bank's client.export const Bank = BankNoDeps.pipe(Component.provide(BankUI.layer));Before the account opens, the page offers to open it. After, it shows the balance and a deposit button. Bank is the component with BankUI.layer provided, so only the bank’s client is left for the entry.
Test the app
Section titled “Test the app”import { HtmlLocator, HtmlScene } from "effect/ui/html/testing";import { Story } from "effect/ui/testing";import { describe, expect, it } from "@effect/vitest";import * as Effect from "effect/Effect";import * as Option from "effect/Option";import { CustomerId } from "../src/Customer.id.ts";import { NotOpen } from "../src/NotOpen.rejection.ts";import { BankMessage, BankNoDeps, BankUI } from "../src/web/Bank.ts";
const props = { customerId: CustomerId.make("c-2") };const summary = (owner: string | null, balance: number) => ({ state: Option.some({ owner, balance }), cursor: 1,});
describe("the bank app", () => { it.effect("opens the customer's account", () => Effect.gen(function* () { const s = yield* Story.make(BankNoDeps, props); s.loaded("summary", { state: Option.none(), cursor: 0 }) .send(BankMessage.ClickedOpen()) .expectExact(BankUI.RegisterCustomer); expect(s.pending[0]!.command.args).toMatchObject({ input: { customerId: "c-2", name: "c-2" } }); s.resolve(BankUI.RegisterCustomer, { commandId: "page:0", reply: undefined, receipt: { stream: "Customer/c-2", version: 1 }, commits: [{ stream: "Customer/c-2", version: 1 }], }); expect(s.model.error).toBeNull(); }), );
it.effect("deposits, and shows the balance the view reports", () => Effect.gen(function* () { const s = yield* HtmlScene.make(BankNoDeps, props); s.loaded("summary", summary("c-2", 0)) .expect(HtmlLocator.label("Balance")) .toHaveText("Balance: 0.00") .click(HtmlLocator.role("button", { name: "Deposit 10.00" })) .resolve(BankUI.DepositMoney, { commandId: "page:0", reply: { balance: 1_000 }, receipt: { stream: "Account/c-2-main", version: 2 }, commits: [{ stream: "Account/c-2-main", version: 2 }], }) // The balance comes from the view, not from the command's reply. .expect(HtmlLocator.label("Balance")) .toHaveText("Balance: 0.00") .loaded("summary", summary("c-2", 1_000)) .expect(HtmlLocator.label("Balance")) .toHaveText("Balance: 10.00"); }), );
it.effect("shows why a deposit was refused", () => Effect.gen(function* () { const s = yield* HtmlScene.make(BankNoDeps, props); s.loaded("summary", summary("c-2", 0)) .click(HtmlLocator.role("button", { name: "Deposit 10.00" })) .fail(BankUI.DepositMoney, { _tag: "Rejected", commandId: "page:0", rejection: new NotOpen() }) .expect(HtmlLocator.role("alert")) .toHaveText("Rejected"); }), );});A Story drives the component’s update and a Scene drives its view, with no browser or server. Like the domain’s stories, each test says what happened and what came back: every command a step runs stays pending until the test resolves or fails it, and the view’s query has no value until the test loads one.
pnpm vitestbun vitestnpx vitestyarn vitestStart the app
Section titled “Start the app”import * as Domain from "@alchemy.run/domain";import { BrowserHost } from "effect/ui/html";import * as Effect from "effect/Effect";import * as FetchHttpClient from "effect/http/FetchHttpClient";import * as HttpClient from "effect/http/HttpClient";import * as HttpClientRequest from "effect/http/HttpClientRequest";import * as Layer from "effect/Layer";import * as Socket from "effect/socket/Socket";import { BankApi } from "../BankApi.api.ts";import { CustomerId } from "../Customer.id.ts";import { Bank } from "./Bank.ts";
// A stand-in for a login page: `?customer=c-2` picks who you are.const customerId = CustomerId.make(new URLSearchParams(location.search).get("customer") ?? "c-1");
// Sign in, so the browser holds the session cookie for every call and watch.const signIn = Effect.gen(function* () { const client = HttpClient.filterStatusOk(yield* HttpClient.HttpClient); yield* client.execute( HttpClientRequest.post("/api/session").pipe(HttpClientRequest.bodyJsonUnsafe({ customerId })), );});
const BankConnection = Layer.unwrap( signIn.pipe( Effect.orDie, Effect.as( BankApi.layerClient.pipe( Layer.provide(Domain.protocolWebSocket(`${location.origin}/api`)), Layer.provide(Socket.layerWebSocketConstructorGlobal), ), ), ),).pipe(Layer.provide(FetchHttpClient.layer));
const Main = BrowserHost.mount(Bank, { customerId }, document.getElementById("root")!).pipe( Layer.provide(BankConnection),);
Layer.launch(Main).pipe(Effect.runFork);The app signs in first, then mounts with the customer as its props and connects to the Api on its own origin. Domain.protocolWebSocket sends commands over HTTP and opens a WebSocket for each live read.
Serve the app and the Api from one origin
Section titled “Serve the app and the Api from one origin”interface Fetcher { fetch(request: Request): Promise<Response>;}
// Serve the app, and forward /api to the bank: one origin, so the session cookie is first-party.export default { fetch(request: Request, env: { readonly ASSETS: Fetcher; readonly BANK: Fetcher }) { const { pathname } = new URL(request.url); return pathname.startsWith("/api") ? env.BANK.fetch(request) : env.ASSETS.fetch(request); },};The app’s Worker serves the built page and forwards /api to the bank. Sharing one origin keeps the session cookie first-party, so browsers send it.
Deploy the app
Section titled “Deploy the app” Effect.gen(function* () { const bank = yield* BankWorker; return { url: bank.url.as<string>() }; const app = yield* Cloudflare.Website.EffectUI("BankApp", { main: "src/web/worker.ts", env: { BANK: bank }, assets: { runWorkerFirst: ["/api", "/api/*"] }, }); return { url: bank.url.as<string>(), app: app.url.as<string>() }; }),);Cloudflare.Website.EffectUI builds the app with Vite. env: { BANK: bank } gives the app’s Worker a binding to the bank, and runWorkerFirst sends /api through it.
Run it
Section titled “Run it”pnpm alchemy devbun alchemy devnpx alchemy devyarn alchemy devOpen the app URL it prints, with ?customer=c-2: Part 5’s script already gave c-1 an account. Open your account, deposit, and the balance updates as the bank records it. Open a second tab with the same customer: both update together.
pnpm alchemy deploybun alchemy deploynpx alchemy deployyarn alchemy deployYou’ve built a bank: an account that keeps its own rules, views that answer questions, a policy that reacts, an Api that checks who’s asking, and an app that watches it live.