elements
Blog Demos UI Docs 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
  • Releases
Manual / Getting Started/ Conventions

Conventions

elements man start/conventions

Where Elements differs from what you would guess from the outside, and the conventions its own source follows. Read this once before you write a first page and the rest of the manual reads faster.

Project structure

  • Routes are declared in index.ts, not file-based. Folder names under app/pages/ are labels, not URLs.
  • A scaffolded page has index.ts (route only) and template.ehtml (template, event handlers, inline RPC). As a page grows, move its @rpc functions and shared interfaces into a hand-authored services.ts sibling. An @rpc never belongs in a page's index.ts.
  • Scaffold with elements create and treat the scaffold as a guide: fill it in, and do not discard its parts without a good reason.
  • Cross-page services and templates live under app/shared/.
  • Import app source with the #app/... map (#app/pages/..., #app/shared/...), never ../../. #config imports config.
  • Import a page's template extensionless: import html from "./template".
  • Use kebab-case for directories and filenames.

HTML templates

  • TypeScript goes outside template declarations or inside {} expressions, not in <script> tags. A <script> or <style> body evaluates {} like any other element, and e:literal keeps a body as written.
  • Group siblings that share a condition in an ordinary element, such as a <div>. A browser keeps a <template> element's content off the page, so Elements groups with rendered elements.
  • Every page has one <main> around its primary content. Screen readers use it to skip past navigation and headers. It can live in a shared layout template.
  • A site's header, nav and footer live in one layout template with the <main>, all on one page-shell width. A page never sets its own shell width, or the header moves from page to page. A narrower page narrows its content with max-w-2xl or max-w-prose. See Layout (opens in a new tab).
  • Attributes live on the root tag only. <div (form: Form)> inside a template is invalid.
  • <html> is the default-export page and html is a reserved name. Other top-level tags are named templates.
  • e:for keys by the id field. Provide one or the runtime warns and falls back to object identity.
  • The directives are e:for, e:if/e:elseif/e:else, and e:switch/e:case/e:default.
  • Read and write data, not the DOM. el.value = "..." fights the runtime; bind with value={form.x} instead. Use {raw(html)} for unescaped HTML rather than el.innerHTML.
  • Mutating an object's fields in a handler is live. Rebinding is not: a function cannot reassign its caller's variable, so errors = serverErrors inside a handler does nothing. Assign in template scope (onsubmit={() => errors = submit(form)}) or wrap a scalar in { value }.
  • Class arrays drop falsy entries: class={["card", active && "active"]}.
  • The lifecycle hooks are oninit, oninsert, and onremove. Each receives an event object with event.target set to the element.
  • Event handlers are named functions in the same .ehtml file. The inline arrow passes template attributes into one.
  • <form onsubmit={...}> calls e.preventDefault() for you.
  • Give every form control a name: <input name="email" value={form.email}>. A binding does not name it, so an unnamed control is left out of a submit. group bindings are the exception and name their radios for you.
  • Navigate with redirect(url), not window.location. The same call works in a template handler, a route, middleware, and an @rpc. Do not render a session.isLoggedIn() view on a signin page: login is an @rpc, so the session flips and repaints before redirect() runs. Bounce a signed-in visitor from the route instead.

RPC and errors

  • @rpc is the boundary. Once across it, anything downstream can call sql(), tx(), and session freely.
  • One form object per @rpc, with its File[] fields on that same object.
  • Internal errors are wrapped in ServerError before they reach the client. Throw an AppError subclass for a message the client should see.
  • ValidationError(message) covers a single rule and ValidationError(fieldErrors) a per-field map. In a template, direct-assign the result: errors = err.errors, not Object.assign.
  • There is no validate() in @elements/app. Throw ValidationError.

Database

  • sql(), tx(), session.login(), and session.logout() are server-only. Browser code, event handlers and template expressions included, cannot call them: the compiler reports a security error at the call site. Call an @rpc function, and put the server-only call inside it.
  • ${value} interpolations are parameterized, so SQL injection is impossible by construction.
  • sql<T>(...) returns a SqlResult<T>. .all() gives the array, .first() gives T | undefined, and .firstOrThrow(msg) gives a required row.
  • Nesting tx() joins the transaction already in progress, and inner sql() calls join the outer transaction automatically.
  • Write camelCase in SQL. Elements translates at the database boundary, and snake_case still works if you prefer it.
  • Migrations are hot in development and frozen in production.

LiveTable

  • A LiveTable is always live. A page that wants rows once, with no subscription, calls an @rpc that returns them from sql.
  • An optimistic insert(...) paints only the object you pass, so include every field the template reads. Server-generated columns count: timestamps, sequence numbers, and trigger-derived values do not exist client-side yet, so pass a placeholder such as createdAt: new Date(). Omit a displayed createdAt and the cell renders Invalid Date until the broadcast lands.
  • A LiveView is an iterable. filter, sort, map, find, at, and length are the Array methods over a copy of its rows and return plain arrays. A helper that builds its own array from the view is live in an e:for too.
  • Never redirect from a mutation's resetUI. It runs before the write is sent and the row is lost. Redirect after a sync insert(), or use a plain @rpc.

Sync-style

  • The Elements functions that support it (sql, tx, RPC calls and the rest listed in man async) are written sync-style, and the compiler propagates async/await up the call stack. Writing them by hand on those calls fights the transform.
  • For third-party libraries (fetch, Stripe, navigator.clipboard), declare your function async and await those calls directly. Your own async/await is left alone.
  • The xAsync variants (sqlAsync, txAsync, insertAsync) are for promise control such as Promise.all over several calls. A sync-style write persists once sent; navigate on the line after it.

Session

  • Read session values with session.get("userId") or session.getOrThrow("userId") and type them through the SessionData interface. There is no getUserId().
  • A logged-out visitor has no session: no row, no token, no cookie.
  • A template that reads a session method updates when the session changes.

Jobs

  • A job is a class that extends Job. Nothing else registers it: there is no app.job(...) and no tag to write.
  • Suffix job class names with Job, as in SendWelcomeJob.

Tests

  • A test reads top to bottom: create the rows it needs, call the code, check the result. Name it for what the code does, in plain words, not for the requirement it satisfies.
  • Each test creates what it needs and nothing more. A fixture that builds the whole world ties every test in the file to the same rows, so they wait on each other's locks, and a change to any part of it fails them all.
  • Helpers are named functions with typed parameters and a return type, laid out like the tests that call them.

Styling

  • Bare elements are already styled. A <button> is a finished button, and so is an <input type="submit">. Inputs, forms, headings, links, tables, and <code> need no classes.
  • Vary a button with is- modifiers rather than a new class: is-primary/is-ghost/is-danger, is-sm/is-lg, is-block. Render an <a> as a button with class="button is-primary".
  • Setting padding, border, radius, or background on something the design system already styles means rebuilding what exists. Read elements man style and use the class.
  • Custom CSS is for layout the system does not provide: page composition, positioning, section spacing.
  • Text is --ink, --ink-soft or --ink-dim. --ink-faint is for placeholders and decoration: as text it fails contrast, and a page using it scores under 100 on Lighthouse accessibility.

Conventions

  • Always use semicolons in TypeScript and JavaScript.
  • A comment says why, never what the next line already says. No banner comments grouping code, and no boxed dividers or ascii rules. They add noise and rot as code moves.
  • The code must be human readable. Write it for the person who reads it next: one statement per line, a blank line between steps. Code compressed onto a few long lines compiles the same and costs the reader every time the file is opened.
  • Never minify or compress source to save space or tokens. Generated files and data files are the only exception.
  • Lines are at most 100 characters. Only a string literal, a SQL template literal or data may run longer.
  • Every block has braces and its body on its own indented lines, even a single statement. No if (done) return; and no one-line { ... } body. An object or array literal with three entries or fewer may sit on one line:
Blocks
if (!user) { return; } const origin = { x: 0, y: 0 };
  • One variable per declaration. Write const a = 1, b = 2 as two lines.
  • A ternary picks between two plain values. Never nest one, and never put logic in its branches: use if.
  • Keep functions short, around 50 lines, and return early rather than nesting.
  • Names say what a thing is. Single letters are for loop indexes only.
  • Template HTML is multiline and indented, one element per line. An element with more than three attributes puts one attribute per line:
Template layout
<ul class="posts"> <li e:for={post of posts}> <a href={post.url}>{post.title}</a> </li> </ul> <input type="email" name="email" value={form.email} required >
  • A template expression is a call or a property read, as in {post.title} or {formatDate(post.createdAt)}. Logic moves into a function in the same file.
  • CSS puts one selector per line and one declaration per line:
Rule layout
.post-title, .post-meta { margin: 0; color: var(--ink-soft); }
  • Type the rows you read, sql<Row>(...), and the values you pass. any hides the mistakes the compiler exists to catch.
  • Environment names are an open set: any name works, with its own config/env/<name>.env and deploy.env.<name> block. ENV defaults to development locally, and elements deploy defaults to production. Code that depends on where the app runs branches on isDeployMachine(), never on the environment name.
  • Write every insert the same way, whatever the number of columns: each column on its own line, ) values ( on one line, then each value on its own line in the same order, so the nth value sits under the nth column:
Insert layout
sql(` insert into signups ( name, email, fileName ) values ( ${name}, ${email}, ${file?.name} ) `);
  • Lay out select, update and delete by clause: select, from, each join, where, group by, order by, limit, set and returning each start a line. A clause with several columns, conditions or assignments puts its keyword alone on the line and one item per line under it, with further conditions leading with and or or. A clause with one item stays on its keyword line. Only a bare select ... from <table> stays on one line:
Query layout
sql(` select id, name from users where active = ${true} and orgId = ${orgId} order by createdAt desc `);
Prev Database and MigrationsNext Deploy, Licensing, Support
Product
Manual Pricing Compare
Company
History Contact
Legal
Privacy Policy Acceptable Use Terms License Agreement
© Elements Dev Corporation 2026