Skip to content

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.

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.

URLs carry a content hash and answer If-None-Match with 304. Third-party files travel with their licence notices.

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>
}
}

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 with on, is refused (an inline handler is script from a string, and the page policy forbids it). The values of href, action, src and similar go through the URL check.
  • URLs. Relative references and http, https, mailto and tel pass. javascript:, data:, vbscript: and a scheme hidden by whitespace become about: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 with el.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 homeUrl or loginUrl, 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 patch
err = 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 name
err = 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.

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.

  • A handled Datastar request always answers 200 with at least one patch, because Datastar applies no other status. An expected failure patches the error where it belongs (the form again, with aria-invalid and the message linked by aria-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 with 303.
  • A modal dialog the answer must close is replaced, not morphed. Datastar’s morph removes the open attribute but leaves a showModal() dialog in the top layer, which keeps the page inert.
  • A session that has expired is detected by the document: a Datastar fetch answered 401 navigates to <login path>?returnTo=<current page> (the parameter name is configurable).
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.

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 document policy is the strict policy with two differences:

  • script-src adds 'unsafe-eval', because Datastar compiles each data-* expression with the Function constructor. With it removed, the drawer cannot open.
  • style-src-attr 'unsafe-inline', because the kit has a few style attributes. <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.

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).

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).

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/).

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.css

Keep 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.

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, tel and relative URLs through. That covers src, href, action, formaction, poster and any attribute whose name contains src, url or uri (also after data-), whether written in a template or passed as spread attributes. Anything else, an image data: URL included, is replaced by about:invalid#TemplFailedSanitizationURL: the page still renders and the image is simply missing. Wrap a value the application built or checked itself in templ.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 rendered style="..." attribute as text must expect it.

After upgrading, search the rendered pages for TemplFailedSanitization: it is the only trace a refused value leaves.

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})
  • Build loads the assets (fwui.WithAssets(assets.WithPrefix("/ui/assets/"))), builds the views, and creates the routes GET <prefix>{file} and GET /icons/lucide-sprite.svg. fwui.CompressAssets() serves the files compressed; wrap the server in compress.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 a Failure. 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 (status 200, one error flash patch). A native request writes nothing and the handler re-renders the form when f.Rerender() is true, with status f.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}))

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/live
func (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))
})
}

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.

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.

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.