Reference · Therapy.jl + WasmTarget.jl
API Reference
Core reactive primitives, control flow, @island WasmGC compilation, Astro-style view transitions, and full-stack server APIs. Try them live on the Examples page.
Signals
create_signal(initial)
reactivityCreate a reactive signal returning a (getter, setter) tuple. Reading the getter inside effects or memos tracks it automatically. Supports Int64, Bool, Float64, and String lowered directly to WasmGC types.
# Primitive signals compile to Wasm globals
count, set_count = create_signal(0) # Int64 -> i64
active, set_active = create_signal(true) # Bool -> i32
temp, set_temp = create_signal(98.6) # Float64 -> f64
# Heap signals compile to WasmGC references
query, set_query = create_signal("") # String -> WasmGC refcreate_effect(() -> ...)
reactivityRun an owner-scoped side effect whenever any tracked signal dependency changes. Disposed automatically when its owning scope cleans up. Use js() to call browser APIs such as console.log.
create_effect(() -> js("console.log('count:', \$1)", count()))
# Runs immediately on mount and re-runs whenever count() changescreate_memo(() -> ...)
reactivityCreate a cached derived value compiled to WasmGC. Recomputes only when tracked dependencies change. Supports primitive and heap return types including Int64, Float64, String, and Vector{String}.
# Primitive memo cached as i64
doubled = create_memo(() -> count() * 2)
# Vector{String} memo cached as a WasmGC ref
filtered = create_memo(
() -> begin
q = lowercase(query())
result = String[]
for i in 1:length(items)
if startswith(lowercase(items[i]), q)
push!(result, items[i])
end
end
result
end,
)batch(() -> ...)
reactivityDefer effect flushes until all signal writes in the block complete. DOM event handlers are auto-batched; call batch explicitly in timers or async callbacks.
# Event handlers are auto-batched (dependent effects fire once)
:on_click =>
() -> begin
set_a(a() + 1)
set_b(b() + 10)
end
# Explicit batch for timers or async callbacks
batch(
() -> begin
set_a(1)
set_b(2)
end,
)on_mount(() -> ...)
lifecycleRun a callback once after the island hydrates into the DOM. Unlike create_effect, it does not track dependencies and never re-runs.
on_mount() do
js("document.getElementById('search-input').focus()")
endon_cleanup(() -> ...)
lifecycleRegister teardown logic for an @island or Julia component scope. Inside islands, cleanups wire into island._therapyUnsubs and execute automatically before View Transition DOM swaps.
on_cleanup() do
js("clearInterval(\$1)", timer_id())
endControl Flow
Show(condition; fallback = ...) do ... end
control flowConditional DOM rendering. Inserts and removes real DOM nodes rather than toggling CSS visibility. Accepts a bare signal getter or a closure compiled to WasmGC, plus an optional fallback VNode.
visible, set_visible = create_signal(1)
Show(visible; fallback = P("Nothing to show.")) do
P("Mounted in the DOM.")
end
# Closure condition compiled to WasmGC
Show(() -> count() > 5) do
P("Count is above 5.")
endcreate_selector(signal) & BindClass(sel, key, on_cls, off_cls)
reactivityO(1) selection primitive for keyed lists. When signal changes, only the previously selected row and newly selected row update their class attribute.
selected, set_selected = create_signal(Int64(0))
is_selected = create_selector(selected)
Tr(
:class => BindClass(is_selected, row.id, "active", ""),
Td(A(:on_click => () -> set_selected(row.id), row.label)),
)For(items; key = fn) do item ... end
control flowKeyed list diffing compiled to WebAssembly (WasmGC). Passing key = r -> r.id uses longest increasing subsequence diffing to keep existing DOM rows in place across swaps, shuffles, updates, and removals, clones new rows from a static <template>, and delegates item click handlers automatically.
Table(Tbody(
For(rows; key = r -> r.id) do row
Tr(
:class => BindClass(is_selected, row.id, "danger", ""),
Td(row.id),
Td(A(:on_click => () -> set_selected(row.id), row.label)),
Td(A(:on_click => () -> remove_row(row.id), "Remove")),
)
end,
))Components
function Name(args...) ... end
ssrPlain Julia functions returning VNodes are SSR components. They run at build or request time with full access to Julia packages and ship zero WebAssembly.
using DataFrames: DataFrame, names, eachrow
function SummaryTable(df::DataFrame)
cols = names(df)
rows = [string.(collect(row)) for row in eachrow(df)]
return Table(
Thead(Tr(
For(cols) do col
Th(col)
end,
)),
Tbody(
For(rows) do row
Tr(
For(row) do cell
Td(cell)
end,
)
end,
),
)
end@island [hydrate = :idle | :eager | :visible] function Name(; kwargs...) ... end
macroMark an interactive component to compile into an external streaming WebAssembly (.wasm) file via WasmTarget.jl. Choose hydrate = :eager to wire up above-the-fold controls immediately, :idle (default) to load when the browser is idle, or :visible to defer until scrolled into view via IntersectionObserver.
@island hydrate = :eager function Counter(; initial::Int = 0)
count, set_count = create_signal(initial)
doubled = create_memo(() -> count() * 2)
create_effect(() -> js("console.log('count:', \$1)", count()))
return Div(
Button(:on_click => () -> set_count(count() + 1), "+"),
Span(count),
Span("doubled: ", doubled),
)
endApp(...; favicon, head_extra, prism_languages, config_file) & preview(app)
appConfigure <head> metadata identically across dev, run, build, and preview. Pass config_file = "therapy.toml" to reload declarative fields live during dev without restarting Julia. Use julia app.jl preview --port 4175 to inspect a built dist/ directory locally.
app = App(
routes_dir = "src/routes",
components_dir = "src/components",
title = "My App",
favicon = "/favicon.svg",
head_extra = "<meta name=\"theme-color\" content=\"#1c7322\">",
prism_languages = ["julia", "bash"],
config_file = "therapy.toml",
)
Therapy.run(app)dev(app; port, host, async) & serve(app)
appStart the instant-boot dev server with lazy on-demand WasmGC compilation, a persistent two-tier .therapy/cache/islands/ cache, live Tailwind CSS HMR, disk-backed static mounts, and structured error overlays. Pass async = true from the REPL or tests to get a DevServerHandle you can shut down with close(handle). Query /_therapy/status or /_therapy/wait?since=<rev> from scripts and editors to check build health.
# Interactive REPL / programmatic dev server
handle = dev(app; port = 8080, async = true)
# ... edit routes, islands, CSS, static files, or therapy.toml ...
close(handle)
# Production full-stack Julia server (SSR + API + WebSockets)
serve(app; port = 8080, host = "0.0.0.0")js(code::String, args...)
interopCall JavaScript from WasmGC via generated module imports. Interpolate signal or memo arguments with $1, $2, and so on. No-op during Julia SSR.
js("document.documentElement.classList.toggle('dark')")
js(
"console.log('count:', \$1, 'doubled:', \$2)",
count(),
doubled(),
)
js("localStorage.setItem('key', \$1)", count())Routing
File-Based Routing
routingFiles in src/routes/ return a zero-argument function producing VNodes. File paths map directly to URLs, serve via SSR, or pre-render into a standalone interactive app during build.
# Directory structure -> URLs
src/routes/index.jl # /
src/routes/getting-started.jl # /getting-started/
src/routes/examples/index.jl # /examples/Client Navigation (View Transitions)
routingFollowing the Astro View Transitions model, internal link clicks fetch the target HTML, diff <head>, swap #page-content inside document.startViewTransition(), update active nav links, and re-hydrate incoming <therapy-island> elements.
# Automatic navigation lifecycle:
# 1. Intercept internal <a> click (hash links scroll natively)
# 2. Fetch target HTML and diff <head> title + meta tags
# 3. Swap #page-content inside document.startViewTransition()
# 4. Re-hydrate islands and dispatch 'therapy:router:loaded'
# 5. Header / elements outside #page-content persist without flashingNavLink(href, children...; class, active_class, inactive_class, exact)
routingRender an anchor tag whose active and inactive classes stay synchronized automatically across client-side navigations.
NavLink(
"/examples/",
"Examples";
class = "tv-pill",
active_class = "tv-pill-on",
inactive_class = "",
)
NavLink("/", "Home"; exact = true, active_class = "tv-pill-on")Hash Anchors & Base Paths
routingHash links (href="#signals") bypass the client router so native browser scrolling and history work without <base href>. Set base_path on App for subpath deployments like GitHub Pages.
A(:href => "/Therapy.jl/examples/", "Examples") # Soft navigation
A(:href => "#signals", "Jump to Signals") # Native hash scroll
A(:href => "https://julialang.org", :target => "_blank", "Julia") # ExternalHTML Elements
Div, Span, Button, Input, Canvas, ...
domAll standard HTML and SVG tags are exported as capitalized Julia functions. Attributes use :symbol => value pairs, and DOM events use :on_click, :on_input, and friends.
Div(
:class => "space-y-3",
H2("Interactive controls"),
Button(:on_click => () -> set_count(count() + 1), "Increment"),
Input(:type => "range", :min => "1", :max => "50", :value => n, :on_input => set_n),
Canvas(:width => 800, :height => 400),
)Includes Div, Span, P, A, Button, Input, Form, Label, H1-H6, Strong, Em, Code, Pre, Ul, Ol, Li, Table, Thead, Tbody, Tr, Th, Td, Header, Footer, Nav, MainEl, Section, Article, Details, Summary, Figure, Figcaption, Img, Svg, Canvas, and RawHtml.
Middleware
compose_middleware(handler, middleware)
middlewareHigher-order HTTP middleware pipeline inspired by Oxygen.jl. Each middleware wraps a handler as handler -> (req -> response). The first middleware in the vector is outermost.
function timing_middleware(handler)
return function (req::HTTP.Request)
t0 = time()
res = handler(req)
@info "request" target = req.target ms = round((time() - t0) * 1000; digits = 1)
return res
end
end
pipeline = compose_middleware(base_handler, [timing_middleware, CorsMiddleware()])CorsMiddleware(; kwargs...)
middlewareHandle OPTIONS preflight requests and attach CORS headers to responses.
cors = CorsMiddleware(
allowed_origins = ["https://myapp.com"],
allowed_headers = ["*"],
allowed_methods = ["GET", "POST", "OPTIONS"],
allow_credentials = true,
max_age = 86400,
)RateLimiterMiddleware(; rate_limit, window)
middlewareFixed-window per-IP rate limiter returning HTTP 429 when exceeded and setting standard X-RateLimit-* and Retry-After headers.
limiter = RateLimiterMiddleware(rate_limit = 100, window = 60)BearerAuthMiddleware(validate_token; header, scheme)
middlewareExtract a Bearer token from the Authorization header, invoke validate_token(token), return 401 on failure, and attach the validated user to req.context[:user].
validate(token) = token == "secret" ? Dict("role" => "admin") : nothing
app = App(middleware = [CorsMiddleware(), BearerAuthMiddleware(validate)])API Routes
create_api_router(routes)
serverDefine JSON HTTP endpoints with path parameters and per-route middleware. Handlers receive (req, params) and return JSON-serializable data, an HTTP.Response, or nothing (204).
api = create_api_router([
"/api/users" => Dict(
"GET" => (req, params) -> ["user1", "user2"],
"POST" => (req, params) -> json_response(Dict("id" => 1); status = 201),
),
"/api/users/:id" => Dict(
"GET" => (req, params) -> Dict("id" => parse(Int, params[:id])),
),
"/api/protected" => Dict(
"GET" => handler,
:middleware => [BearerAuthMiddleware(validate)],
),
])json_body / text_body / form_body / query_params / json_response
serverRequest body extractors and JSON response builders for API handlers.
json_body(req) # Dict or nothing
json_body(req, MyPayload) # Typed struct
text_body(req) # Raw String or nothing
form_body(req) # Form Dict or nothing
query_params(req) # Dict{String, String}
json_response(Dict("ok" => true); status = 200) # HTTP.ResponseStatic Files
staticfiles(app, folder, mountdir = "static"; headers, loadfile)
serverWalk folder and cache every file as a GET route under mountdir with MIME inference via MIMEs.jl. Static mounts are also copied into output_dir during build(app).
staticfiles(
app,
joinpath(@__DIR__, "public"),
"assets";
headers = ["Cache-Control" => "public, max-age=3600"],
)dynamicfiles(app, folder, mountdir = "static"; headers, loadfile)
serverLike staticfiles, but re-reads file contents from disk on every request during development. Page routes always take precedence over static mounts.
dynamicfiles(app, "./content", "blog"; headers = ["Cache-Control" => "no-cache"])WebSockets
websocket(path, handler; middleware)
realtimeRegister per-path WebSocket handlers with optional path parameters and upgrade middleware.
# using Therapy, HTTP
websocket("/ws/room/:id") do ws, params
room_id = params[:id]
for msg in ws
HTTP.WebSockets.send(ws, "[$room_id] " * String(msg))
end
endsubscribe / unsubscribe / broadcast_channel / broadcast_all
realtimeChannel-based pub/sub and connection lifecycle callbacks (on_ws_connect, on_ws_disconnect, on_channel_message) multiplexed over WebSockets.
subscribe(conn, "chat")
broadcast_channel("chat", Dict("type" => "message", "text" => "hello"))
on_ws_connect() do conn
println("Connected: $(conn.id)")
endHot Module Replacement
julia --project=. app.jl dev
toolingOS-level file watching via FileWatching recompiles only the edited @island, pushes fresh WasmGC bytes over WebSocket, and preserves matching signal globals across the swap. CSS edits swap stylesheets in place without reloading.
# Component .jl change -> surgical WasmGC recompile + signal state preserved
# input.css change -> Tailwind rebuild + in-place stylesheet swap
# Route .jl change -> route reload + browser refresh
julia --project=. app.jl dev