Duolith docs

0033. A screen guards itself with guard(...), and screens share state by name

  • Status: Accepted (Mik, 17 Nov 2026)
  • Date: 2026-11-14
  • Decided by: integrator (internal only), pending Mik's approval
  • Planning item: none

Context

Some screens need a condition, such as being signed in, and should send the user elsewhere until it holds. With no server, the check runs on the device, and it must react: signing out while on the screen should leave it. The condition usually lives in state several screens read (the sign-in screen sets it, the account screen checks it), but each screen runs its own script, so until now no state outlived a screen.

Decision

Guards. A page or layout script calls guard(check) at its top:

guard(() => signedIn || "/sign-in?next=/account");

The check returns a string to redirect there (replacing the screen, so back does not return to it), any truthy value to allow the screen, and false, null or undefined to show the not-found screen in its place. The router runs the page's setup, asks every new guard (outermost layout first) before building anything on the page, and asks again whenever the state a guard read changes while its screen is in front, and when back shows a kept screen again (its own guards and its layouts'). A guard in a layout protects every screen inside it. Ten redirects in a row stop with an error at the built-in not-found screen, rather than looping or leaving the app empty. A redirect stays on this site: a guard that names another one is refused (decision 0031). guard() outside a script's top level throws.

Shared state. state(initial, { shared: "signed-in" }) is one value for every screen that declares state with that name, for as long as the app runs. It is an ordinary state variable in every other way (assignment, bind:checked), so the compiler needs no change. The first declaration's initial value wins.

Alternatives considered

OptionWhy not
A guard in front matter or the route tableA second place to look, and it could not read the page's state
export const guard = ...Pages run per screen and cannot export (E0147); a call reads like props()
Guards that return { redirect } objectsLonger for the common cond || "/path" form
Shared state from .ts modules imported by pagesThe build does not compile project .ts files yet, and the compiler would have to track state across modules
Shared state in the root layout, passed downLayouts cannot pass props to the screens in their slot, and the sign-in screen may not be inside the layout

Consequences

A guard runs on the device and is not security: data must still be protected by the server that holds it. The page's setup runs before its guards are asked, so a guarded page should not start work it cannot undo at the top of its script (resources it starts are stopped when the screen is turned away). The glossary needs guard, and a word for shared state if "shared" is not enough.