elements
Start Docs Blog Demos UI Pricing
Elements Manual
  • Getting Started
    • Project Layout
    • At a Glance
    • More Patterns
    • Database and Migrations
    • Conventions
    • Deploy, Licensing, Support
  • CLI
  • Build
  • Browser
  • Packages
  • TypeScript
  • Elements HTML
  • Assets
  • RPC
  • Router
  • Session
  • Database
  • Migrations
  • LiveTable
  • Channel
  • Jobs
  • Email
  • Payments
  • JSON
  • Async
  • Style
  • UI
  • JSOC
  • Config
  • Tests
  • Logs
  • Deploy
  • Editors
  • Recipes
  • Licenses
  • Issues
  • Changelog
Manual / Getting Started/ More Patterns

More Patterns

elements man start/patterns

On This Page

  • RPC
  • SQL and Transactions
  • Auth, Errors, Validation
  • Session
  • Sync-style and Async
  • Channels
  • Routes
  • Jobs and Cron
  • Tests
  • Config
  • CSS Style

Short examples of the features most apps need next: sessions, forms, validation, email, and scheduled work.

Features the example in start/at-a-glance does not show. Each subsection names the manual topic that covers it in full.

RPC

Use /** @rpc */ to make a function callable from the browser. The compiler rewrites browser call sites into network requests and removes the body from the browser bundle. Call them like normal functions, with no await and no fetch. Every call is type checked at build time.

app/pages/home/services.ts
import { sql, ValidationError } from "@elements/app"; import { Comment } from "./models"; /** @rpc */ export function searchComments(query: string): Comment[] { if (query.length < 2) { throw new ValidationError("query too short"); } return sql<Comment>(` select * from comments where text ilike ${"%" + query + "%"} order by createdAt desc limit 20 `).all(); }

An @rpc function runs on the server. The RPC body, the helpers it calls, and the helpers those call can all call sql(), tx() and session.login(). Browser-reachable code that calls them is a compile error pointing at the call site.

RPC go in services.ts next to a page, or in app/shared/services/<topic>.ts for cross-page use. Never in a page's index.ts. Full topic: elements man rpc.

SQL and Transactions

Usage
import { sql, tx } from "@elements/app"; let user = sql<User>(` select * from users where id = ${id} `).first(); let users = sql<User>(` select * from users where active = ${true} `); for (let u of users) { /* ... */ } tx(() => { let u = sql<User>(` insert into users ( name ) values ( ${name} ) returning * `).firstOrThrow("insert returned no row"); sql(` insert into auditLog ( event, userId ) values ( 'user_created', ${u.id} ) `); });

${value} interpolations auto-extract as parameterized arguments at build time; SQL injection is impossible by construction. sql<T>(...) returns a SqlResult<T>: .all() for the array, .first() for T | undefined, .firstOrThrow(msg) for a required row. tx(fn) commits on return, rolls back on throw, and returns what fn returned. Every sql() inside joins the same connection. Full topic: elements man database.

Auth, Errors, Validation

Usage
import { session, AuthError, NotFoundError, ForbiddenError, ValidationError, } from "@elements/app"; session.isLoggedInOrThrow(); // throws AuthError if not logged in if (!isAdmin(session.getOrThrow("userId"))) { throw new ForbiddenError(); } throw new NotFoundError(`room ${id} not found`); // 404 throw new ForbiddenError(); // 403 throw new ValidationError("qty must be positive"); // 422, single rule throw new ValidationError({ email: ["must be a valid email"] }); // 422, per-field

AppError subclasses are safe = true: their messages are sent to the browser. Internal errors are wrapped in ServerError before being sent.

  • AuthError (401): unauthenticated
  • ForbiddenError (403): authenticated but not permitted
  • NotFoundError (404): resource missing
  • ValidationError (422): invalid input (string or FieldErrors<T> map)
  • NotAcceptableError (406): request body unparseable
  • PartitionMismatchError (400): a LiveTable row outside the view's partition
  • ServerError (500): safe wrapper for internal errors

An error thrown from an @rpc is thrown at the browser call site as the same class. Catch with instanceof in a try/catch around the call site. validate() does not exist. Throw ValidationError directly. Full topic: elements man rpc.

Session

The current user's session. Available everywhere on the server and in the browser. Read methods are reactive in the browser; a template that reads session.isLoggedIn() updates when the user logs in or out.

Usage
import { session } from "@elements/app"; session.login({ userId, userName }); // server-only session.logout(); // server-only session.isLoggedIn(); // boolean. reactive in browser. session.get("userId"); // SessionData["userId"] | undefined. reactive. session.getOrThrow("userId"); // same, but throws if absent.
Example
<nav> <a e:if={session.isLoggedIn()} href="/account">{session.get("userName") ?? "account"}</a> <a e:else href="/login">log in</a> </nav>

Session values are typed through the SessionData interface. Declare the keys your app stores in app/types/session.d.ts:

app/types/session.d.ts
declare module "@elements/app" { interface SessionData { userId: string; userName: string; role: "admin" | "user"; } } export {};

session.get(key) returns SessionData[key] | undefined; getOrThrow(key) throws when the key is absent. There is no getUserId() / getUserName(); read session.get("userId"). A logged-out visitor has no session at all (no row, no token, no cookie), so there is no anonymous visitor id: a visitor has an identity only after session.login(). Full topic: elements man session.

Sync-style and Async

The Elements functions that support it (sql, tx, calls to @rpc functions, channel.notify, LiveTable mutations, session.login, and the rest listed in man async) are written sync-style. The compiler rewrites each call to its async variant (sql → await sqlAsync) and propagates async/await up the call stack automatically, including across function-expression arguments to schedulers (setTimeout, addEventListener).

For third-party libraries, which the compiler does not rewrite (fetch, Stripe SDK, navigator.clipboard), declare your function async and await those calls directly. The build leaves your manual async/await alone. For explicit promise control (e.g. Promise.all), import the xAsync variant (sqlAsync, txAsync, etc.).

Channels

Typed pub/sub from the server to every listening browser, on every app server. LiveTable uses Channel internally. Use Channel directly to send messages that are not table rows (push notifications, presence, side-channel events).

Usage
import { Channel, session } from "@elements/app"; interface Alert { userId: string; level: "info" | "warning"; text: string; } const alerts = new Channel<Alert>("alerts"); export default function route(req: Request, res: Response) { return new html({ alerts: alerts.listen({ filter: (a) => a.userId === session.getOrThrow("userId") }), }); } /** @rpc */ export function postAlert(text: string) { alerts.notify({ userId: session.getOrThrow("userId"), level: "info", text, }); }

listen() returns a subscribed listener. Pass it to a template or return it from an @rpc; the browser receives a listener that subscribes to the channel as it arrives. Full topic: elements man channel.

Routes

URL patterns are declared explicitly in index.ts, not file-based. Folder names under app/pages/ are labels.

index.ts
import { App } from "@elements/app"; import config from "#config"; import home from "#app/pages/home"; import roomsShow from "#app/pages/rooms-show"; import apiRouter from "#app/api"; const app = new App(); app.route("/", home); app.route("/rooms/:id", roomsShow); app.route("/api", apiRouter); // mount a sub-router // data route app.route("/api/rooms", () => sql(` select id, name from rooms `)); app.start(config);

URL patterns use the URLPattern standard. Dynamic segments: :name. A page route returns new html({...}). A data route returns serializable data (Elements JSON), or writes to res directly with res.write / res.end. AppError subclasses work the same in routes and @rpc. A LiveTable or listener returned from a route or RPC subscribes in the browser as it arrives, with no call from your code.

Fetch initial page data inside the route, not from the browser via @rpc after the page loads. Full topic: elements man router.

Jobs and Cron

app/jobs/send-welcome.ts
import { Job, email } from "@elements/app"; import { WelcomeEmail } from "#app/emails/welcome"; export class SendWelcomeJob extends Job<{ to: string }> { static maxAttempts = 5; run() { email({ to: this.fields.to, subject: "welcome", body: new WelcomeEmail(), }); } }
index.ts
app.cron("every 5m", "rank posts", () => new RankPostsJob().schedule()); app.cron("every day at 2am", "archive", () => new ArchiveOldRowsJob().schedule());

.schedule() inside tx() joins the surrounding transaction. The job becomes visible only after commit. The build server runs the worker; jobs are stored in Postgres. One machine runs each cron tick (Postgres-arbitrated leader election). Keep cron callbacks small; enqueue and let the worker do the work. Extend Job and suffix the class name with Job. Full topic: elements man jobs.

Tests

Tests run as part of every build; failures show up alongside compile errors. Each test() body runs inside a Postgres transaction that rolls back at the end, so writes never pollute the test database.

app/lib/users.test.ts
import { test, assert, equal, sql } from "@elements/app"; test("users", () => { test("create", () => { let user = sql<User>(` insert into users ( name ) values ( 'alice' ) returning * `).firstOrThrow("insert returned no row"); equal(user.name, "alice"); }); test("does not see the previous test's row", () => { let count = sql<{ n: number }>(`select count(*) as n from users where name = 'alice'`).firstOrThrow(); equal(count.n, 0); }); });

Files: test.ts or <name>.test.ts, anywhere in the tree. Run elements test -json to read the test results. test() calls nest for grouping. Assertions: assert, equal, errorf, fatalf. Full topic: elements man tests.

Config

config.jsoc is evaluated at build time. JSOC is JSON with comments, unquoted keys, trailing commas, and an env(...) function. Missing required env vars or wrong types fail the build, not the deploy.

config.jsoc
{ database: { name: "my_app", host: env("DB_HOST", "127.0.0.1"), // default when unset port: env("DB_PORT", 5433), // default when unset }, session: { expires: "30d", // sliding expiry }, }

Env vars come from the OS at startup. After startup, edit config/env/<env>.env for hot reload. Full topic: elements man config.

CSS Style

Every page's style.css imports app/shared/styles/page.css, which imports @elements/ui: the templates (elements man ui) and the stylesheet they share: design tokens for colors, spacing, type, and radii, a reset, finished styles for bare HTML elements, and classes for buttons, forms, cards, callouts, pills, and tabs.

Use a template first. Before writing CSS for an element or component the @elements/ui stylesheet already styles, read elements man style and use the class or bare element it documents. Bare elements are already styled. A <button> is a finished secondary button; <input>, <form>, headings, links, tables, and code are all styled with no classes. Vary a button with is- modifiers rather than a new class: is-primary, is-ghost, is-danger for intent, is-sm/is-lg for size, is-block for full width. Each modifier sets one property of the button (intent, size or width), and modifiers combine in any order. Write custom CSS only for layout the system doesn't provide (page composition, positioning, spacing between sections). Maintain the Elements style language in new apps unless the user directs otherwise. Full topics: elements man ui and elements man style.

Restyling a page that already exists

Delete the markup you are replacing before you write layout CSS for it, and let the deletion and the new rules go out in the same save.

New layout CSS applied to the markup a scaffold wrote puts your widths and spacing on the scaffold's hero, makes a column the wrong size, and makes sections overlap. The user is watching every save, so for the next several minutes they see that page instead of a page being built. The scaffolded AGENTS.md says never to save markup and style it afterwards; the same rule applies when the markup is already there.

Colour is the exception. A palette change applies to any markup without changing its layout, so make it first, in a save of its own. The user sees the whole page change colour at once.

Prev At a GlanceNext Database and Migrations
Product
Manual Pricing Compare
Company
History Contact
Legal
Privacy Policy Acceptable Use Terms License Agreement
© Elements Dev Corporation 2026