Web & UI/Live Components

Live Components

Server-driven real-time UI over WebSocket and SSE: signals, actions, hooks, PushEvent, Redirect, and wire error codes.

livegithub.com/fletchhq/fletch/live· fletch docs show live-components

On this page

Fletch Live renders HTML on the server using Crest templates, streams minimal DOM diffs over WebSocket (with automatic SSE+POST fallback), and keeps state and business logic in Go.

Mounting Live Components

Register a Live component on the app’s router with fletch.MountLive, which adds the page’s GET and its POST event route under one name. fletch make live tasks counter writes this line into the module’s routes.go:

func (m *Module) routes(a *fletch.App) {
	fletch.MountLive(a.Router(), "tasks.counter", "/tasks/counter", func() live.Component { return &Counter{} })
}

fletch.Live(fn, opts...) returns the same endpoint as a plain http.Handler when you register routes yourself, for example a.Router().Handle(http.MethodGet, "/tasks/counter", h) plus the matching POST.

Live components also support embeddable Live roots inside standard server-rendered pages and a Head() hook for setting per-view <head> tags (such as page titles or metadata) on initial HTTP render.

Component Lifecycle

A Live component is a Crest view with a Mount method. The struct’s template (counter.crest for Counter) compiles to its Render(ctx context.Context, w io.Writer) error and slot-diffing methods, so you do not write Render by hand. Mount takes a *live.Ctx; actions are methods that take a context.Context, which at run time is the session’s *live.Ctx. Events sent from JavaScript hooks or $fletch reach an optional HandleEvent:

package tasks

import (
	"context"
	"encoding/json"

	"github.com/fletchhq/fletch/live"
)

type Counter struct {
	Count int
}

func (c *Counter) Mount(ctx *live.Ctx) error { return nil }

func (c *Counter) Inc(ctx context.Context) error {
	c.Count++
	return nil
}

func (c *Counter) HandleEvent(ctx *live.Ctx, name string, payload json.RawMessage) error {
	if name == "reset" {
		c.Count = 0
		return ctx.PushEvent("toast", map[string]string{"message": "Counter reset"})
	}
	return nil
}
<!-- counter.crest -->
<section>
  <p>Count: {c.Count}</p>
  <button on:click={c.Inc}>+</button>
</section>

In Crest templates, bind DOM events to server action methods with on:click={c.Inc}. From Mount, an action, or HandleEvent, call these on the *live.Ctx (an action gets it from its context.Context argument):

  • PushEvent(name, payload) error to dispatch a custom fletch:event:<name> browser event to JS hooks or Alpine’s $fletch.on.
  • Redirect(url) error to navigate the browser after a server-side state change.

Signals

Signals separate fast client-side reactive UI state from full server re-renders.

  • Local signals hold client-owned UI state (such as modal visibility, active tab, or draft input text). Client mutations apply locally without a server round-trip.
  • Shared signals stay synchronized with server updates pushed from Go.

Crest binds signals directly on elements:

<button type="button" on:click={c.Save()}>Save</button>
<p show={$dirty}>Unsaved changes</p>
<span text={$status}></span>
<div class:is-open={$open}></div>
<input type="text" bind:value={$query} />
<input type="checkbox" bind:checked={$archived} />

Invalid bind:value or bind:checked bindings fail at compile time with diagnostic W0309.

When using Alpine.js in standalone Live setups (without fletch.WithAlpine), pass live.WithSignalNames(...) so Live writes data-f-signals on the root element and $fletch.signal can look up signals by field name.

Client Interop: Hooks, data-f-ignore, and Alpine.js

Use three mechanisms to integrate browser-only JavaScript with Live DOM patches:

  • data-f-hook: attaches a client-side JavaScript lifecycle hook to an element managed by Live (useful for charting libraries, rich text editors, or clipboard APIs).
  • data-f-ignore: tells Live’s DOM patcher to skip reconciling the element’s subtree. Pair data-f-ignore with a stable id so client-managed DOM and third-party widget instances survive parent re-renders. It only changes how the DOM is patched; it is not a security boundary.
  • Alpine.js with $fletch: combines lightweight client state with Live actions, PushEvent, and entangled signals. See Alpine.js & Live Interactivity for setup, CSP rules, and DOM patch lifecycle guarantees.

Security and Session Binding

Live validates CSRF tokens and Origin headers before upgrading WebSocket connections or accepting SSE+POST frames.

Session Eviction

Authenticated Live connections bind to the user’s session through a binding key. When a user logs out or a session is revoked, (*live.Handler).EvictBinding(key) ends every Live session with that key: the client gets error W6013 (session revoked) and the connection closes with WebSocket status 1008. In a Fletch app, (*fletch.App).EvictLiveBinding(key) does the same across every Live handler the app serves, and app.SessionCookie(...) calls it for you whenever it logs out or revokes a session.

A frame that arrives with a binding that does not match the session’s (for example after the user signs in as someone else) is refused with W6007.

PCI Card-Name Lint (W0314)

fletch check inspects Live templates with diagnostic W0314 to flag form inputs whose names indicate payment card data (such as card number or CVV fields). Collect card data in your payment provider’s hosted iframe or element so card numbers never reach your server, Live component state, or wire frames. data-f-ignore does not do this: it only stops Live from patching a subtree, and inputs inside it are still part of your page and your forms.

PHI Redaction in live_state

Tag sensitive component struct fields with fletch:"phi" so diagnostic endpoints (such as /_fletch/ax/live_state) and inspection snapshots redact protected health information automatically.

Transport, Shutdown, and Deploys

Live connects over WebSocket by default and falls back to SSE+POST automatically when corporate proxies or network policies block WebSockets.

During graceful shutdown (including ECS task drains on SIGTERM), fletch.Run closes active Live WebSockets cleanly with close code 1001 (Going Away) and drains SSE streams so clients reconnect smoothly to healthy instances.

Checking Deploy Compatibility with fletch state plan

Before rolling out a release, run fletch state plan to compare Live component state schemas against the previous build. Each component is classified into one of three deploy outcomes:

Classification Meaning
resume State schema is compatible; existing client sessions resume in place.
rerender Template or non-breaking state layout changed; sessions keep state and perform a fresh render.
remount Breaking state change; clients remount the component cleanly on reconnect.

Wire Error Codes

Live returns structured error codes over the wire and to $fletch.call rejections:

Code Meaning
W0403 Event refused
W0429 Rate limited
W6001 Session limit reached
W6002 Mailbox or backlog overflow
W6003 Component mount failed
W6004 Unknown, forged, or stale component ref
W6005 Action or HandleEvent failed
W6007 Auth session binding mismatch
W6008 Subscription handler failed
W6009 Recover failed
W6010 Field validation error
W6011 Stream closed
W6013 Session revoked: the binding was evicted after logout or revocation
W6014 Client pre-connect queue overflow (>32 events) or connection lost while a call was in flight