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/ Conventions

Conventions

elements man start/conventions

On This Page

  • Project Structure
  • HTML Templates
  • RPC and Errors
  • Database
  • LiveTable
  • Sync-Style Code
  • Session
  • Jobs
  • Tests
  • Styling
  • Source Code Conventions

How Elements differs from other web frameworks, from project structure to styling, 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 go 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 be written in a shared layout template.
  • A site's header, nav and footer are written in one layout template with the <main>, all on one page-shell width. In a site with that shared layout, 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. An app of one page with no shared header puts page-shell and its width on its own <main>. See Layout (opens in a new tab).
  • Template attributes are declared on a template's 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 keys each item by 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. A value set with el.value = "..." is not copied to the bound variable; bind with value={form.x} and assign form.x instead. Use {raw(html)} for unescaped HTML rather than el.innerHTML.
  • Mutating an object's fields in a handler updates the template. Reassigning a variable does 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"]}. That is for an HTML element. The class attribute of a template from @elements/ui, such as <Icon>, is a string.
  • 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 function in the event attribute passes template attributes to the handler.
  • <form onsubmit={...}> calls e.preventDefault() itself.
  • 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 themselves.
  • 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 changes and the template re-renders before redirect() runs. Redirect a signed-in visitor from the route instead.

RPC and Errors

  • Code inside an @rpc function runs on the server. It, and every function it calls, can call sql(), tx(), and session.
  • One form object per @rpc, with its File[] fields on that same object.
  • Internal errors are wrapped in ServerError before they are sent to 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 it to snake_case for Postgres, and snake_case still works if you prefer it.
  • In development, editing an applied migration re-runs it against the local database. On a deploy machine each migration runs once.

LiveTable

  • A LiveTable is always live. A page that needs rows once, with no subscription, calls an @rpc that returns them from sql.
  • insert(...) shows the row in the browser at once, before the server answers, and it renders only the object you pass. 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 server's broadcast of the saved row arrives.
  • 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 Code

  • 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. Do not write async or await on those calls yourself: the compiler adds them.
  • 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. Extending Job is what registers it: there is no app.job(...) call and no build 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 inserts every row any test in the file needs makes every test use the same rows, so the tests wait on each other's row locks, and a change to any part of the fixture 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.

Source Code 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 go out of date as code moves.
  • The code must be human readable. Never write long single-line code. 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 be written 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 is directly 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