Web & UI/Alpine.js & Live Interactivity
Alpine.js & Live Interactivity
Opt-in Alpine.js 3.17.6 with strict CSP defaults, the $fletch Live bridge, signal entanglement, and DOM patch lifecycle.
On this page
- Enabling Alpine in a Fletch App
- 1. Configure fletch.New
- 2. Register the Crest Plugin
- 3. Render <f:alpine /> in the Layout
- CSP Build vs. Standard Build
- The $fletch Bridge API
- Pre-Connect Queueing and Error Handling
- Listening to Server Events
- Signal Entanglement with $fletch.signal
- Live Patch Lifecycle and DOM Ownership
- Crest Attribute Parity and W0313
- Standalone Usage Without the fletch Meta-Module
The github.com/fletchhq/fletch/alpine package embeds official Alpine.js 3.17.6 (both @alpinejs/csp and standard alpinejs, MIT licensed) along with the $fletch Live bridge plugin. No Node.js, npm, or external CDN is required. Assets are served under alpine.Prefix (/_fletch/alpine/<name>.<hash>.js) with content-hashed URLs and CSP nonces from router/secure.
Alpine is strictly opt-in. An application that omits fletch.WithAlpine mounts no /_fletch/alpine/* routes and links none of the embedded Alpine scripts into its binary.
Enabling Alpine in a Fletch App
Enabling Alpine requires three steps: pass fletch.WithAlpine to fletch.New, register the <f:alpine /> compiler element, and place <f:alpine /> in your layout <head>.
1. Configure fletch.New
Pass fletch.WithAlpine() in bootstrap/app.go to enable the default CSP-safe build (@alpinejs/csp), or pass alpine.Standard() to opt into the standard build:
// Default: @alpinejs/csp (works with strict CSP, no 'unsafe-eval')
app := fletch.New(
fletch.WithAlpine(),
)
// Explicit opt-in: standard alpinejs build
app := fletch.New(
fletch.WithAlpine(alpine.Standard()),
)
fletch.WithAlpine mounts the script routes, writes data-f-signals on every Live root so $fletch.signal can resolve signals by name, and registers an alpine subsystem in fletch ax inspect.
2. Register the Crest Plugin
Add alpine.Element() to the element list in fletch.plugins.go, next to the scaffold’s icon.Element():
//go:build fletchbuild
package main
import (
"github.com/fletchhq/fletch/cmd/fletchbuild"
"github.com/fletchhq/fletch/elements/alpine"
"github.com/fletchhq/fletch/elements/icon"
)
func main() {
fletchbuild.Main(fletchbuild.Elements(icon.Element(), alpine.Element()))
}
fletch gen rebuilds the cached compiler in .fletch/bin/compiler when this file changes.
3. Render <f:alpine /> in the Layout
Place <f:alpine /> inside <head> in ui/layouts/app.crest, outside any Live root:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<slot name="head" />
<f:alpine />
</head>
<body>
<slot />
<slot name="scripts" />
</body>
</html>
<f:alpine /> emits two deferred <script> tags carrying the request’s CSP nonce: the $fletch bridge plugin loads first, followed by Alpine. Rendering <f:alpine /> without fletch.WithAlpine configured fails with alpinert.ErrNotEnabled.
CSP Build vs. Standard Build
| Build | Option | Script CSP Requirement | Allowed Expressions |
|---|---|---|---|
@alpinejs/csp (default) |
fletch.WithAlpine() |
script-src 'self' 'nonce-...' |
Property access, method calls, object literals, assignments |
alpinejs (standard) |
fletch.WithAlpine(alpine.Standard()) |
Requires 'unsafe-eval' in secure.Config |
Full JavaScript expressions, including arrow functions |
Under the default @alpinejs/csp build, inline attributes support property lookups, method calls, object literals, and direct assignments. Arbitrary inline JavaScript and arrow functions are rejected by the CSP parser. Define multi-step behavior with Alpine.data("name", function () { ... }) inside a nonce’d <script> tag or same-origin JS file on the alpine:init event:
document.addEventListener("alpine:init", function () {
Alpine.data("dropdown", function () {
return {
open: false,
toggle() {
this.open = !this.open;
},
close() {
this.open = false;
},
};
});
});
<div x-data="dropdown" @click.outside="close">
<button type="button" @click="toggle">Menu</button>
<div x-show="open" x-cloak>
<slot />
</div>
</div>
When alpine.Standard() is enabled, Fletch serves both builds. <f:alpine /> emits the standard build by default, while <f:alpine mode="csp" /> still selects @alpinejs/csp for specific layouts. Requesting <f:alpine mode="standard" /> when alpine.Standard() was not passed fails with alpine.ErrStandardDisabled.
fletch check emits diagnostic W0315 when alpine.Standard() is configured and no Go code in the application adds 'unsafe-eval' to secure.Config.
The $fletch Bridge API
The $fletch magic targets the closest enclosing [data-f-live] root element. Every method works even if Alpine initializes before the Live transport finishes connecting.
| Member | Behavior |
|---|---|
$fletch.push(name, payload) |
Sends name and payload to the enclosing component’s HandleEvent(c, name, payload) without waiting for a response. |
$fletch.call(name, payload) |
Sends name and payload to HandleEvent(c, name, payload) and returns a Promise that resolves after the server’s DOM diff is applied. |
$fletch.on(name, fn) |
Subscribes to server-pushed events from c.PushEvent(name, payload) (fletch:event:<name>). Automatically removes the listener on Alpine teardown and returns nothing so x-init="$fletch.on(...)" is safe. |
$fletch.signal(name) |
Entangles an Alpine property with a Live signal by case-insensitive Go field name (matching $open in Crest). |
$fletch.root |
The closest enclosing [data-f-live] DOM element, or null outside a Live root. |
Pre-Connect Queueing and Error Handling
Before the WebSocket join completes or the SSE stream fires open, $fletch buffers up to 32 push and call invocations in order and flushes them once connected. A 33rd pre-connect event rejects immediately with code W6014 (too many events before connect).
If the connection drops while a $fletch.call is in flight, its Promise rejects with W6014 (connection lost). Because the drop may have occurred after the server received the frame, the server may or may not have executed HandleEvent.
$fletch.call always routes through HandleEvent(c, name, payload) and never invokes Go action methods directly by name. When HandleEvent returns an error (such as W6005), the Promise rejects with an Error carrying code, msg, and field properties:
document.addEventListener("alpine:init", function () {
Alpine.data("renameForm", function () {
return {
title: "",
saving: false,
error: "",
async submit() {
this.saving = true;
this.error = "";
try {
await this.$fletch.call("rename", { title: this.title });
} catch (err) {
this.error = err.msg || "Save failed";
} finally {
this.saving = false;
}
},
};
});
});
Listening to Server Events
Subscribe with $fletch.on in an Alpine.data init() hook to react to c.PushEvent(name, payload) calls from Go. Keeping the callback in JavaScript keeps it working under the default @alpinejs/csp build, which rejects inline function expressions in x-init:
document.addEventListener("alpine:init", function () {
Alpine.data("savedNotice", function () {
return {
notice: "",
init() {
this.$fletch.on("saved", (detail) => {
this.notice = detail.message;
});
},
};
});
});
<div x-data="savedNotice">
<p x-show="notice" x-text="notice"></p>
</div>
$fletch.on returns undefined, so it is also safe as an x-init expression under alpine.Standard(), where Alpine would otherwise call a returned function as cleanup. The listener is removed automatically when Alpine destroys the element tree.
Signal Entanglement with $fletch.signal
$fletch.signal(name) binds an Alpine property directly to a Live signal using the Go field name (case-insensitive, the same naming used by $open in Crest). Changes stay synchronized across Alpine state, Live’s client signal store (show=, text=, class:, bind:), and server Set updates.
Writes from Alpine remain client-side, matching the semantics of bind:. Use Local signals for Alpine-owned UI state such as open/closed panels or active tabs, and call $fletch.call when a mutation must run on the server.
<div x-data="{ open: $fletch.signal('open') }">
<button type="button" @click="open = !open">Toggle Drawer</button>
<aside x-show="open" x-cloak>
<slot />
</aside>
</div>
Live Patch Lifecycle and DOM Ownership
Live and Alpine coordinate automatically during DOM updates:
- Before removing elements during a replaced branch, removed keyed row, or full re-render, Live calls
Alpine.destroyTreeso componentdestroy()hooks run and$fletch.onlisteners detach cleanly. - After inserting new elements, Live calls
Alpine.initTreebefore dispatching anyPushEventpayloads delivered in the same frame. - Keyed rows (
{for ... key <expr>}) that move positions preserve their Alpine state. - Elements marked with
data-f-ignoreand a stableidkeep their Alpine state across re-renders.
Keep DOM ownership separated between Live and Alpine. Do not put Crest dynamic expressions inside <template x-if>, <template x-for>, x-html, or x-text. Wrap subtrees whose structure Alpine controls in data-f-ignore:
<div id="tag-editor" data-f-ignore x-data="tagEditor">
<template x-for="tag in tags" :key="tag">
<span x-text="tag"></span>
</template>
</div>
Crest Attribute Parity and W0313
Crest passes standard quoted Alpine attributes through as static HTML without treating { ... } inside quotes as Go template expressions. Attributes such as x-data="{ open: false }", :class="{ 'is-open': open }", @click.outside="open = false", x-on:keydown.escape.window="open = false", x-transition:enter="...", and x-cloak can sit directly alongside Crest class:, on:, and bind: directives:
<div
x-data="{ open: false }"
@click.outside="open = false"
x-on:keydown.escape.window="open = false"
class:is-loading={c.Loading}
>
<button type="button" @click="open = !open" :class="{ 'is-open': open }">
Actions
</button>
</div>
To prevent script injection, Crest blocks dynamic Go expressions inside Alpine directive attributes (x-data={...}, @click={...}, :class={...}, and any x-* attribute except x-transition* and x-ref) with compiler diagnostic W0313. Pass server-rendered values through data-* attributes or entangle them with $fletch.signal:
<!-- Blocked by W0313 -->
<div x-data={c.InitialJSON}></div>
<!-- Safe: read from data-* in Alpine.data init(), or bind with $fletch.signal -->
<div data-initial-tab={c.Tab} x-data="tabs"></div>
Standalone Usage Without the fletch Meta-Module
Applications using crest, router, and live directly without github.com/fletchhq/fletch can wire the Alpine bundle manually:
b := alpine.New() // or alpine.New(alpine.Standard())
// Mount the embedded script handler at each path returned by b.Paths()
handler := b.Handler()
for _, p := range b.Paths() {
mux.Handle(p, handler)
}
// Inject the tag renderer into request context for <f:alpine />
ctx = alpinert.WithTags(ctx, func(ctx context.Context, mode string) (string, error) {
return b.Tags(alpine.Mode(mode), nonce)
})
alpinert is github.com/fletchhq/fletch/elements/alpine/rt. Its TagsFunc receives the render context and the mode attribute of <f:alpine /> as a string ("", "csp", or "standard"); convert it to alpine.Mode for Bundle.Tags. nonce is the CSP nonce of the current request.
When mounting standalone Live components, pass live.WithSignalNames(...) so Live writes data-f-signals on the root element for $fletch.signal lookups.
See Live Components for full server lifecycle and wire error details, and Crest Templates for template attribute rules.