elements
Blog Demos UI Docs Pricing
Elements Manual
  • Getting Started
  • 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
    • Todo App
    • Todo App: Markup and Styles
    • Authentication
    • Form Validation
    • Signup with Email Confirmation
    • Signup Wizard
    • Admin Roles
    • File Upload
    • Serving Assets From the Database
    • Live Comments
    • Likes / Votes Toggle
    • Shared Lists
    • Team-Partitioned Table
    • Chat Rooms
    • Typing Indicator
    • Grouped Feed Without Flicker
    • Unread Counts
    • Room Presence
    • Collaborative Canvas
    • Infinite Scroll Feed
    • Bidirectional Partition
    • Search and Filter
    • Admin Table
    • Markdown Blog
    • Public and Admin Views
    • Cron Cache
    • Live Dashboard
    • Live Updates From Any Write
    • Marketing Page
    • Status Indicators
    • Markdown Editor
    • Time Ago
  • Licenses
Manual / Recipes/ Admin Roles

Admin Roles

elements man recipes/admin-roles

Role-gated admin pages and rpc. The users table has a role column of an enum type. A shared helper reads that column on every request and throws if the caller is not an admin. The admin page route and the admin RPC both call the helper at the top of the function. The signin and signup pages come from the authentication recipe; this recipe layers role gating over them.

Migration

Terminal
elements create migration 'add users' -tables=users
app/migrations/<timestamp>-add-users.migration.sql
-- add users -- Auto-update updatedAt on row changes. create or replace function touchUpdatedAt() returns trigger language plpgsql as $$ begin new.updatedAt = now(); return new; end; $$; create type userRole as enum ('user', 'admin'); create table users ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), handle text not null unique, passwordHash text not null, role userRole not null default 'user' ); create trigger usersTouchUpdatedAt before update on users for each row execute function touchUpdatedAt();

The userRole Postgres enum type restricts the column to 'user' and 'admin'. The database rejects any other value at insert or update time. To add a role later, run alter type userRole add value 'editor' in a follow-up migration.

Admin helpers

app/shared/services/admin.ts
import { sql, session, ForbiddenError } from "@elements/app"; export function isUserAdmin(userId: string): boolean { return !sql(` select 1 from users where id = ${userId} and role = 'admin' `).empty(); } export function isUserAdminOrThrow() { session.isLoggedInOrThrow(); if (!isUserAdmin(session.getOrThrow('userId'))) { throw new ForbiddenError("admin access required"); } }

isUserAdmin returns a boolean for callers that need to branch on role. isUserAdminOrThrow is the guard for admin routes and rpc. It first calls session.isLoggedInOrThrow(), which throws (401) if the request has no session. If the request is signed in but the user is not an admin, it throws ForbiddenError (403). The two errors carry different meanings to the browser, so distinguishing them matters: AuthError says the user needs to sign in, ForbiddenError says the user is signed in but lacks the role.

Both functions call sql, which is a server-only primitive, so the Elements build pipeline keeps both functions out of the browser bundle automatically. No build-tag annotation is needed on user code.

Admin page

Terminal
elements create page admin

That writes app/pages/admin/{index.ts, template.ehtml, style.css, test.ts} and prints the /admin route line to add to index.ts. The setRole RPC and the AdminUser interface go in template.ehtml, and index.ts imports them from ./template. The admin guard is the one thing shared with other pages, so it stays in app/shared/services/admin.ts.

app/pages/admin/index.ts
import { Request, Response, sql } from "@elements/app"; import { isUserAdminOrThrow } from "#app/shared/services/admin"; import admin, { AdminUser } from "./template"; export default function route(req: Request, res: Response) { isUserAdminOrThrow(); let users = sql<AdminUser>(` select id, handle, role from users order by createdAt desc `).all(); return new admin({ users }); }
app/pages/admin/template.ehtml
import "./style.css"; import { sql } from "@elements/app"; import { Badge } from "@elements/ui/badge"; import { Button } from "@elements/ui/button"; import { Table, TableHead, TableCell } from "@elements/ui/table"; import { isUserAdminOrThrow } from "#app/shared/services/admin"; export interface AdminUser { id: string; handle: string; role: string; } /** @rpc */ export function setRole(userId: string, role: 'user' | 'admin'): AdminUser[] { isUserAdminOrThrow(); sql(` update users set role = ${role} where id = ${userId} `); return sql<AdminUser>(` select id, handle, role from users order by createdAt desc `).all(); } <html class="page-admin" (users: AdminUser[])> <main class="page-shell"> <h1>users</h1> <Table label="users"> <table> <thead> <tr> <TableHead>handle</TableHead> <TableHead>role</TableHead> <TableHead align="end">actions</TableHead> </tr> </thead> <tbody> <tr e:for={u of users}> <TableCell>{u.handle}</TableCell> <TableCell> <Badge variant={u.role === 'admin' ? "primary" : "outline"}>{u.role}</Badge> </TableCell> <TableCell align="end"> <Button e:if={u.role === 'user'} size="sm" onclick={() => users = setRole(u.id, 'admin')}> promote </Button> <Button e:else size="sm" onclick={() => users = setRole(u.id, 'user')}> demote </Button> </TableCell> </tr> </tbody> </table> </Table> </main> </html>

The list is a Table (opens in a new tab) with a Badge (opens in a new tab) for the role, primary for an admin and outline for a user, and a small Button (opens in a new tab) per row for the action. All three are @elements/ui templates, which every new app has; elements man ui is the chapter.

isUserAdminOrThrow() appears on the route handler and on the rpc. The route guard blocks the page render. The RPC guard blocks the operation. Each layer runs independently, so both carry the same check.

The RPC returns the refreshed list. The template reassigns users from the return value, the e:for re-renders, and the new role shows up without a page reload.

The template does not check isUserAdmin anywhere. By the time the template renders, isUserAdminOrThrow() has already let the request through or thrown. A non-admin never sees the rendered HTML.

Routes

Register the page in index.ts:

index.ts
import admin from "#app/pages/admin"; // ... app.route("/admin", admin);

Notes

  • Creating the first admin. setRole requires an existing admin to call it. Bootstrap by running update users set role = 'admin' where handle = 'you' once with elements db -sql (add -remote=production for a deploy machine). For a local admin account that exists on every fresh database, put the insert in a migration tagged @migration env=development (see elements man database/seeds), so the demo admin never reaches production. After that, the first admin can promote others through the UI.
  • Defense in depth. Protect both routes and RPC functions. Routes guard the page render; RPC guard the operation itself. Apply the same role check at the top of each.
  • More than two roles. Add a value to the enum with alter type userRole add value 'editor' and update the helpers. For role hierarchies (admin can do everything an editor can), order them in a const ROLES = ['user', 'editor', 'admin'] as const and compare by index inside a userHasRoleOrThrow(role) helper.
  • Per-row permissions. Roles gate types of action; per-row ownership gates specific rows. The two compose: call isUserAdminOrThrow() and then if (row.ownerId !== session.getOrThrow('userId')) { throw new AuthError(); } for an admin route that still only edits rows the admin owns.
  • Reactive hide in templates. A signed-in non-admin browsing the public site can have admin-only links hidden with <a e:if={session.isLoggedIn() && currentUserIsAdmin}>.... Pass currentUserIsAdmin: boolean from the route handler. Don't call isUserAdmin() from the template; it's server-only.
Prev Signup WizardNext File Upload
Product
Manual Pricing Compare
Company
History Contact
Legal
Privacy Policy Acceptable Use Terms License Agreement
© Elements Dev Corporation 2026