Server-rendered pages
Server-rendered pages are the optional alternative to the Nuxt UI package. Use them for an application that is mostly forms, lists and detail pages and that does not want a JavaScript build. Nothing else in the framework depends on them. The normative text is the server-rendered UI specification.
Pages are plain HTML that works without JavaScript: links, GET and POST forms, post/redirect/get. Datastar 1.0.5 adds the drawer, dialogs and live patches. The same kit markup is rendered in both languages, so the Go and Java implementations (see Packages) pass the same fixtures.
Packages
Section titled “Packages”github.com/flowcatalyst/framework/go/ui is its own Go module, so templ, goldmark, bluemonday and brotli
stay out of the core module. It requires no framework module: an application that is not built on the
framework can take it alone. The framework wiring (fwui) is a second module that requires the core module
and go/ui.
| Package | What it is |
|---|---|
kit |
One templ component per kit spec, Props structs that mirror the specs, and the hardening below |
ds |
The Datastar 1.0 adapter on net/http |
assets |
The static files (kit stylesheet, Datastar, icon sprite, the islands) with hashed URLs, ETags and 304 |
md |
Markdown to sanitised HTML (goldmark with GFM, bluemonday) |
views |
Pages and answers: one template as a full document or a patch, Patches, the page policy, the flash cookie, the theme cookies |
i18n |
Catalogs and locale resolution (languages) |
compress |
Opt-in Brotli and gzip for pages, Datastar streams and static files |
fwui |
The framework wiring: Declare and Build, the static routes, the shell user from the session, the use-case error mapper |
The module is released by tag (go/ui/vX.Y.Z; fetch with go get github.com/flowcatalyst/framework/go/ui@vX.Y.Z). The templ files are compiled by templ (v0.3.1118, a tool of
the module) and the generated *_templ.go files are committed. An application that takes this module takes its templ
version too, and must regenerate its own *_templ.go files with it: see What templ does to attribute
values.
One dependency; the BOM pins the versions:
<dependency> <groupId>io.flowcatalyst.framework</groupId> <artifactId>framework-ui</artifactId></dependency>An application writing its own JTE pages adds the plugin that compiles templates to Java during the build, so nothing is compiled at run time and no template source is on the production classpath:
<plugin> <groupId>gg.jte</groupId> <artifactId>jte-maven-plugin</artifactId> <version>${jte.plugin.version}</version> <configuration> <sourceDirectory>${project.basedir}/src/main/jte</sourceDirectory> <contentType>Html</contentType> </configuration> <executions> <execution> <id>generate-templates</id> <phase>generate-sources</phase> <goals><goal>generate</goal></goals> </execution> </executions></plugin>UiModule serves the module’s files at /fw-ui/ and the icon sprite at /icons/lucide-sprite.svg:
UiAssets assets = UiAssets.load();return App.builder() .module(new UiModule(assets)) .module(new OrdersUiModule(assets)) .module(new JettyHttpModule());URLs carry a content hash and answer If-None-Match with 304. Third-party files travel with their licence
notices.
Components
Section titled “Components”The kit has one component per spec in the UI kit (buttons, inputs, tables, dialogs, drawers, pickers, the app shell, Markdown, the code editor and diagram islands, and more). Every fixture of the kit renders identically in Go and Java after normalisation.
A component is a templ function taking its props: kit.Button(kit.ButtonProps{...}). A field is the
spec’s prop name with a capital first letter, and its json tag is the prop name. The default slot is
the templ children; a named slot is a templ.Component field.
@kit.TR(kit.TRProps{ID: "row-" + o.ID}) { @kit.TD(kit.TDProps{}) { <a href={ kit.SafeURL("/orders/" + o.ID) } data-id={ o.ID } data-on:click__prevent={ OpenOrder }>{ o.Customer }</a> }}Kit has one method per component and Props one record per component, named as the specs’ tables
(class is cls and for is forId, because they are Java keywords). An absent prop is null or
false. A slot is a gg.jte.Content: Markup.text("...") for escaped text, Markup.raw("...") for markup
you vouch for, or a content block in a JTE template.
${Kit.tableRow(new Props.TR(false, false, "row-" + o.id(), null, null), @`${Kit.tableCell(new Props.TD(0, null, null), @`<a href="/orders/${o.id()}" data-id="${o.id()}" data-on:click__prevent="${OrdersUi.OPEN_ORDER}">${o.customer()}</a>`)}`)}What the kit refuses
Section titled “What the kit refuses”The kit enforces specification section 3 where it renders. A refusal throws (Java) or panics (Go), so a request that reaches a bad value fails with a 500 before anything is written.
- Extra attributes go through one function (
kit.Attrs/Markup.attrs). A name that is not a plain name, or starts withon, is refused (an inline handler is script from a string, and the page policy forbids it). The values ofhref,action,srcand similar go through the URL check. - URLs. Relative references and
http,https,mailtoandtelpass.javascript:,data:,vbscript:and a scheme hidden by whitespace becomeabout:invalid#blocked. - Ids, signals and paths that enter a Datastar expression are code. They are validated and refused
otherwise. User data goes into plain attributes (
data-id) and is read withel.dataset.id, never put in an expression. - Unknown variants and sizes are errors, never replaced by a default.
- Raw markup has one door (
kit.Raw/Markup.raw). Never pass request data to it. - No application paths. The kit names none. A permission-denied dialog needs a
homeUrlorloginUrl, and the app shell takes every link from its props.
An XSS sweep test puts a payload into every string prop of every fixture, one at a time, in both languages.
Pages: one template, a full page or a patch
Section titled “Pages: one template, a full page or a patch”A page handler answers a navigation with a full document and a request with Datastar-Request: true with
an event stream that patches the same content. The content is wrapped in <div id="fw-page">, which the
patch morphs. A link, a form post and a live update share one template.
v, err := views.New(a, views.WithTitleSuffix(" - Demo"), views.WithLogin("/auth/login", ""), // the parameter defaults to returnTo views.WithFlashes(map[string]kit.FlashMessageProps{"saved": {Kind: kit.FlashSuccess, Summary: "Saved."}}), views.WithShell(func(r *http.Request) kit.AppShellProps { /* ... */ }))
err = v.Page(w, r, "Orders", content) // 200, or a Datastar patcherr = v.Page(w, r, "Orders", form, views.WithStatus(422), // a re-rendered form views.WithPageFlashes(kit.FlashMessageProps{Kind: kit.FlashError, Summary: "Check the details."}), views.WithScripts("fc-code-editor.js")) // island scripts, by asset nameerr = v.Stream(w, r, func(p *views.Patches) error { // several patches return errors.Join(p.Inner("#rows", rows), p.Flash(kit.FlashSuccess, "Saved.", ""))})Everything is rendered into a buffer first. An error or a panic writes nothing, so a response is never half-sent.
Views views = Views.builder(assets).titleSuffix(" - Orders demo").shell(r -> shell()).build();
return views.page(r, status, "Orders", Pages.orders(new OrdersView(q, l, form)), flashes);A handler that answers more than the page streams patches:
p.outer(Pages.list(new OrdersView(q, l, NewOrderForm.empty())));p.replace("#new-order", Pages.newOrderDialog(NewOrderForm.empty()));p.flash("success", "Order created.", o.customer() + " (" + o.id() + ")");p.focus("new-order-open");A page that uses an island lists its script by asset name; each becomes a <script type="module"> after
Datastar:
return views.page(r, 200, "Editor", Markup.text("x"), List.of(), List.of("fc-code-editor.js", "fc-diagram.js"));The patch operations are outer, inner, append, prepend, replace, remove, page, flash,
signals, focus, closeDialog, redirect and replaceURL. redirect and replaceURL accept a local
path only (one leading /, not // or /\, no control character or backslash). focus and closeDialog
take a validated element id.
Answering rules
Section titled “Answering rules”- A handled Datastar request always answers
200with at least one patch, because Datastar applies no other status. An expected failure patches the error where it belongs (the form again, witharia-invalidand the message linked byaria-describedby). Mutating actions are sent with{retryMaxCount: 0}. - The same routes answer a native form post. A validation failure re-renders the page with status
422. A success redirects with303. - A modal dialog the answer must close is replaced, not morphed. Datastar’s morph removes the
openattribute but leaves ashowModal()dialog in the top layer, which keeps the page inert. - A session that has expired is detected by the document: a Datastar fetch answered
401navigates to<login path>?returnTo=<current page>(the parameter name is configurable).
Native form posts, 303 and the flash cookie
Section titled “Native form posts, 303 and the flash cookie”The sessions CSRF guard accepts only JSON bodies by default (anything else is 415). A route a page posts
to natively is declared as a form route, which also accepts application/x-www-form-urlencoded and
multipart/form-data. The provenance checks (Fetch Metadata and Origin) run first and are unchanged,
bearer requests are not checked, and every other route stays JSON-only. See sessions and
login.
Register the route with httpfw.AcceptForms(). On success, v.SeeOther(w, r, path, key) answers 303 to
a local path with the flash cookie; a Datastar request cannot follow a 303, so it gets status 200 and a
redirect patch instead.
Declare the route with RouteOptions.acceptForms(). On success, views.seeOther(r, "/orders?x=1", "saved") answers 303 with Location and a fw_flash cookie, or, for a Datastar request, 200 with the
cookie and a redirect patch.
The flash cookie holds a key, never text. The messages are registered when the views are built
(WithFlashes / Views.Builder.flash). The next document looks the key up, renders the message in the flash
stack (#flash-stack) and clears the cookie. A key must match [a-z0-9-]{1,64} and be registered, or setting
it fails and nothing is sent. An unknown key in a request cookie renders nothing, so request text can never
become a message. The cookie is Path=/; HttpOnly; SameSite=Lax; Max-Age=60 and Secure; plain-HTTP cookies
are allowed only when the application opts in (WithPlainHTTPCookies / plainHttpCookies) and, in Go, the
request is plain HTTP; fwui opts in when APP_ENV is local or test.
A Datastar action carries no token, so a POST handler needs a same-origin check, and a real application also authorises every handler.
The page policy
Section titled “The page policy”The document policy is the strict policy with two differences:
script-srcadds'unsafe-eval', because Datastar compiles eachdata-*expression with theFunctionconstructor. With it removed, the drawer cannot open.style-src-attr 'unsafe-inline', because the kit has a fewstyleattributes.<style>elements and external styles stay'self'.
Also set: frame-ancestors 'none', base-uri 'none', form-action 'self', object-src 'none',
Cross-Origin-Opener-Policy: same-origin, a Permissions-Policy that denies camera, microphone and
geolocation, and nosniff. There is no inline script and no <style> element, so no nonce is needed; an
application’s own inline script is allowed by hash (WithScriptHash / scriptHash). The weaker script policy
is the main reason to prefer the Nuxt UI package for untrusted content. A Datastar answer is not a document
and carries no policy.
Images from another host (a map’s tiles, for example) are blocked by img-src 'self' data:. An application can
name extra image sources, which follow data: in img-src in the order given, a duplicate once. A source is an https
origin, https://host or https://host:port, optionally with one leading wildcard label (https://*.example.org),
with nothing after the host or port (no path, not even a trailing /). Anything else (*, https:, data:, blob:,
http://..., quotes, ;) is refused at build. Only img-src can be widened, and without the option the policy is
unchanged.
v, err := views.New(a, views.WithImageSources("https://tile.openstreetmap.org"))// or, through the framework wiring: fwui.WithViews(views.WithImageSources(...))views.CSPWithImageSources(hashes, sources) is the builder behind it.
Views views = Views.builder(assets).imageSource("https://tile.openstreetmap.org").build();ViewCsp.policy(hashes, sources) builds the policy; an invalid source makes build() throw IllegalArgumentException.
Datastar helpers
Section titled “Datastar helpers”Package ds has no dependency on the Datastar SDK.
if ds.IsDatastar(r) { sse := ds.NewSSE(w, r) err := errors.Join( sse.Patch(PoolRows(view)), // morphs the element with the same id sse.Patch(PoolCount(view), ds.Inner("#pools-count")), ) return err}Patch renders into a buffer first, so a failing render sends nothing. Options: WithSelector,
WithMode (outer, inner, replace, prepend, append, before, after, remove),
WithViewTransition, WithNamespace, WithEventID, WithRetry. ReadSignals(r, &v) reads the
datastar query parameter for GET, HEAD and DELETE and the JSON body (capped at 1 MiB) for other
methods; bad signals are a *SignalsError with status 400 (413 for a large body).
The HTTP module’s Datastar support (see HTTP) is used by Views and Patches. A
handler normally uses Views and Patches rather than writing events itself.
Theme, icons and the stylesheet
Section titled “Theme, icons and the stylesheet”Dark mode is a dark class on <html>, rendered by the server from the fc_theme (light, dark,
system) and fc_scheme cookies, and the sidebar’s collapsed state from fc_sidebar, so a dark page does
not flash light. Icons reference /icons/lucide-sprite.svg#i-<name>.
kit.css is a Tailwind 4 build (4.3.5) of the kit theme plus the classes the module’s templates use. It is
committed, so building the application never runs Node. An application with its own templates writes its own
input file that imports the kit theme and adds its @source lines (see the UI kit).
The files the module vendors
Section titled “The files the module vendors”Each third-party file travels with its licence notice and a pinned sha256. The current versions are Datastar 1.0.5
(datastar.js), the Lucide icons 1.73.0 (lucide-sprite.svg), Mermaid 12.3.0 (mermaid.min.js) and the Tailwind
4.3.5 build of kit.css. The Go module serves the same files under the prefix you give assets (default /fw-ui/).
Go: pages with your own kit
Section titled “Go: pages with your own kit”An organisation that builds several applications on go/ui may want its own look while the page plumbing stays a
dependency. Keep the module’s kit and add a stylesheet when you only want to change colours, fonts or spacing:
a, err := assets.Load(assets.WithFiles(appFiles, "brand.css"))v, err := views.New(a, views.WithStylesheets("brand.css")) // linked after kit.cssKeep your own copy of the kit (a fork you maintain) when you want to change the markup of the components, the shell, the
bare page wrapper or the flash messages. The document, the flash stack and every flash message are then rendered through
a look.Look (package go/ui/look): views.WithLook(l) replaces the module’s kit.Look{}, views.WithShellComponent(fn)
wraps the page in the application’s own shell (giving it together with WithShell is an error), and
views.WithStylesheets(...) links more stylesheets after the look’s, in order, once each. Flash messages use the shared
types look.Flash and look.FlashKind. With none of these options the output is byte for byte what it was. The Java
module has no such options.
What templ does to attribute values (Go)
Section titled “What templ does to attribute values (Go)”From templ v0.3.1118, two rules change what a page sends. An application regenerates its own *_templ.go files with that
version.
- A URL attribute given a plain string lets only
http,https,mailto,teland relative URLs through. That coverssrc,href,action,formaction,posterand any attribute whose name containssrc,urloruri(also afterdata-), whether written in a template or passed as spread attributes. Anything else, an imagedata:URL included, is replaced byabout:invalid#TemplFailedSanitizationURL: the page still renders and the image is simply missing. Wrap a value the application built or checked itself intempl.SafeURL(...). The kit does this for its own (the brand logo given as SVG). - A style value ends with
;, whatever it is given. A test that compares a renderedstyle="..."attribute as text must expect it.
After upgrading, search the rendered pages for TemplFailedSanitization: it is the only trace a refused value leaves.
Go: the framework wiring
Section titled “Go: the framework wiring”fwui plugs the views into the module lifecycle:
ui := fwui.Declare(app) // declaring: adds the "ui" module, no settings// ...mod, err := ui.Build(b, // in the build function fwui.WithViews(views.WithLogin("/auth/login", ""), views.WithShell(shellFor)))srv, err := httpfw.NewServer(b, web, []*httpfw.Routes{authModule.Routes(), mod.Routes(), pages})Buildloads the assets (fwui.WithAssets(assets.WithPrefix("/ui/assets/"))), builds the views, and creates the routesGET <prefix>{file}andGET /icons/lucide-sprite.svg.fwui.CompressAssets()serves the files compressed; wrap the server incompress.Handler(srv.Handler())for pages and streams.fwui.ShellUser(r)gives the app shell’s user from the session: display name (email, then principal id), email and initials.- Errors.
mod.Fail(w, r, err)maps an error to aFailure. A service error with a 4xx status keeps its message; anything else is a 500 with a generic message, because it may name internals. A Datastar request is answered itself (status200, one error flash patch). A native request writes nothing and the handler re-renders the form whenf.Rerender()is true, with statusf.FormStatus()(422), or returns the error for the framework’s envelope.
f, answered := mod.Fail(w, r, err)if answered { return nil}if !f.Rerender() { return err}return mod.Views().Page(w, r, "Orders", form, views.WithStatus(f.FormStatus()), views.WithPageFlashes(kit.FlashMessageProps{Kind: kit.FlashError, Summary: f.Title(), Detail: f.Message}))Live Datastar updates from Push
Section titled “Live Datastar updates from Push”Server-rendered screens can stay live without client-side polling or custom event hubs by bridging
the framework’s push module directly into a Datastar SSE stream. The bridge
watches one or more client-scoped push topics, debounces rapid bursts (150 ms default), and runs
your render callback to patch only the affected fragment. When push is unavailable or runs on the
platform publish-only driver, it falls back cleanly to a periodic refresh interval (15 s default).
// GET /ui/orders/livefunc (h *Handler) LiveBoard(w http.ResponseWriter, r *http.Request) error { cx := fw.FromRequest(r) return fwui.Live(w, r, h.pushes, cx.Client(), []string{"orders:board"}, func(ctx context.Context, p *views.Patches) error { board, err := h.loadBoard(ctx, cx.Client()) if err != nil { return err } return p.Outer(BoardFragment(board)) })}// GET /ui/orders/livePushLive.stream( pushes, ctx.client(), List.of("orders:board"), patches -> patches.outer(renderBoard(ctx.client())));Compression
Section titled “Compression”In Go, assets.Load(assets.WithCompression()) compresses each CSS, JavaScript and SVG file once per coding
(Brotli 9, gzip 9) on first request and keeps the bytes, so a file is not compressed again per request.
compress.Handler compresses pages and Datastar streams, flushes each event, gives each coding its own
ETag suffix and matches If-None-Match per variant.
Testing and demos
Section titled “Testing and demos”Both languages run the kit’s fixtures against their renderers (all 80 fixture directories) and carry an XSS
sweep. Each has an orders demo with the same pages, URLs, element ids and signals, so one browser check runs
against both: go/ui/fwui/examples/orders-demo-templ and examples/orders-demo-jte. The check drives
Chromium and covers Datastar, the drawer and dialog flow, the page policy, dark mode, no-JavaScript pages and
accessibility.
Not provided
Section titled “Not provided”A login page (the platform hosts login), a CSRF token helper, and rich-text or chart components. The platform’s own
/ui console is built on this module (go/ui), including its brand theming. Known accessibility findings in the kit’s colours (white on the primary
colour, some badges, the page subtitle) are pinned by the browser check as a ratchet.