elements
Start Docs Blog Demos UI 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
  • Issues
  • Changelog
Manual / Recipes/ Public and Admin Views

Public and Admin Views

elements man recipes/public-admin-views

On This Page

  • Migration
  • Services
  • Public route
  • Admin route
  • Routes
  • Notes

Two routes over the same events data. The public route at /events lists upcoming events without auth. The admin route at /admin/events shows the same data plus a create form and per-row delete actions. Both pages open a view on one shared LiveTable. Mutations are gated inside the LiveTable's insert, update, and delete handlers: only admins succeed; the public page never tries to mutate, but if it did the LiveTable would reject the call server-side.

In this recipe everyone reads the same LiveTable and only admins write to it. isUserAdminOrThrow() is called in two places: in the LiveTable's insert, update and delete handlers, where it stops the write, and in the admin route, where it stops the page from rendering. The public route checks neither a session nor a role.

Migration

Terminal
elements create migration 'add events' -tables=events
app/migrations/<timestamp>-add-events.migration.sql
-- add events -- Auto-update updatedAt on row changes. create or replace function touchUpdatedAt() returns trigger language plpgsql as $$ begin new.updatedAt = now(); return new; end; $$; create table events ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), title text not null, description text not null default '', eventDate timestamptz not null ); create index eventsEventDateIdx on events (eventDate asc); create trigger eventsTouchUpdatedAt before update on events for each row execute function touchUpdatedAt();

The eventsEventDateIdx backs the where eventDate >= now() filter and the order by eventDate asc clause. description defaults to the empty string, so the column is not-null and an event with no description stores ''.

Services

Two pages consume the events LiveTable: the public /events route and the admin /admin/events route. Because more than one page imports it, the file is in app/shared/services/ and not in either page's directory. If only the admin page needed it, the declarations would be in that page's template.ehtml.

app/shared/services/events.ts
import { LiveTable, sql } from "@elements/app"; import { isUserAdminOrThrow } from "#app/shared/services/admin"; export interface Event { id: string; createdAt: Date; updatedAt: Date; title: string; description: string; eventDate: Date; } export let events: LiveTable<Event> = new LiveTable<Event>({ select: () => sql<Event>(` select id, createdAt, updatedAt, title, description, eventDate from events where eventDate >= now() - interval '1 hour' order by eventDate asc `), insert: (item) => { isUserAdminOrThrow(); return events.insert(item); }, update: (item) => { isUserAdminOrThrow(); return events.update(item); }, delete: (item) => { isUserAdminOrThrow(); return events.delete(item); }, });

The custom select limits the initial rows to events from the last hour and into the future. The extra hour keeps an event that has already started in the initial rows for an hour after its start time. The select function ignores its (partition, window) arguments because neither route partitions or windows the view. Both the public and the admin route open a view on this same declaration. The public template only reads the view; the admin template also calls insert and delete on it.

Every handler calls isUserAdminOrThrow() first, the guard from elements man recipes admin-roles. It throws when there is no session and when the user is not an admin, so an anonymous browser or a non-admin calling events.insert(...) from a devtools console fails before any SQL runs. The handler then returns the raw auto-SQL on the declaration, events.insert(item) and the rest. The declaration carries an explicit LiveTable<Event> annotation because its initializer refers to it.

Public route

Terminal
elements create page events
app/pages/events/index.ts
import { Request, Response } from "@elements/app"; import events from "./template"; import { events as eventsTable } from "#app/shared/services/events"; export default function route(req: Request, res: Response) { return new events({ events: eventsTable.view() }); }

The public route is unauthenticated. Anyone can open /events and see the upcoming events.

app/pages/events/template.ehtml
import "./style.css"; import { LiveView } from "@elements/app"; import { Item, ItemGroup, ItemContent, ItemTitle, ItemDescription } from "@elements/ui/item"; import { Empty } from "@elements/ui/empty"; import { Event } from "#app/shared/services/events"; <html class="page-events" (events: LiveView<Event>)> <main class="page-shell"> <h1>upcoming events</h1> <ItemGroup label="upcoming events"> <Item e:for={e of events.sort((a, b) => +a.eventDate - +b.eventDate)} variant="outline"> <ItemContent> <ItemTitle>{e.title}</ItemTitle> <time>{e.eventDate.toLocaleString()}</time> <ItemDescription e:if={e.description}>{e.description}</ItemDescription> </ItemContent> </Item> </ItemGroup> <Empty e:if={events.length === 0} title="no upcoming events" /> </main> </html>

The public template reads the view. Each event is an Item, and Empty takes the list's place when nothing is upcoming. There are no mutation buttons. The broadcast still patches the list when an admin adds, edits, or removes a row, so the public page updates live.

Admin route

Terminal
elements create page admin-events
app/pages/admin-events/index.ts
import { Request, Response } from "@elements/app"; import { isUserAdminOrThrow } from "#app/shared/services/admin"; import adminEvents from "./template"; import { events as eventsTable } from "#app/shared/services/events"; export default function route(req: Request, res: Response) { isUserAdminOrThrow(); return new adminEvents({ events: eventsTable.view() }); }

The admin route checks admin status before opening the view for the template. The page never renders for a non-admin; the checks in the LiveTable's handlers reject a non-admin's write wherever it comes from.

app/pages/admin-events/template.ehtml
import "./style.css"; import { LiveView } from "@elements/app"; import { Field } from "@elements/ui/field"; import { Input } from "@elements/ui/input"; import { Textarea } from "@elements/ui/textarea"; import { Button } from "@elements/ui/button"; import { Item, ItemGroup, ItemContent, ItemTitle, ItemDescription, ItemActions, } from "@elements/ui/item"; import { Empty } from "@elements/ui/empty"; import { AlertDialog, AlertDialogFooter, AlertDialogCancel, AlertDialogAction, } from "@elements/ui/alert-dialog"; import { Event } from "#app/shared/services/events"; interface EventInput { title: string; description: string; eventDate: string; } function emptyForm(): EventInput { return { title: "", description: "", eventDate: "", }; } function onSubmit(events: LiveView<Event>, form: { value: EventInput }) { if (form.value.title.trim().length === 0) { return; } if (form.value.eventDate.length === 0) { return; } events.insert( { title: form.value.title.trim(), description: form.value.description.trim(), eventDate: new Date(form.value.eventDate), }, () => form.value = emptyForm(), ); } function onDelete(events: LiveView<Event>, event: Event) { events.delete(event); } <html class="page-admin-events" ( events: LiveView<Event>, private form: { value: EventInput } = { value: emptyForm() }, )> <main class="page-shell"> <h1>events (admin)</h1> <form class="new stack" onsubmit={() => onSubmit(events, form)}> <Field label="title" required> <Input value={form.value.title} /> </Field> <Field label="date" required> <Input type="datetime-local" value={form.value.eventDate} /> </Field> <Field label="description" description="optional"> <Textarea value={form.value.description} rows={3} /> </Field> <Button type="submit" variant="primary">add event</Button> </form> <ItemGroup label="upcoming events"> <Item e:for={e of events.sort((a, b) => +a.eventDate - +b.eventDate)} variant="outline"> <ItemContent> <ItemTitle>{e.title}</ItemTitle> <time>{e.eventDate.toLocaleString()}</time> <ItemDescription e:if={e.description}>{e.description}</ItemDescription> </ItemContent> <ItemActions> <AlertDialog title={`delete "${e.title}"?`} description="Every open events page loses it at once."> <Button slot="trigger" variant="danger" size="sm">delete</Button> <form onsubmit={() => onDelete(events, e)}> <AlertDialogFooter> <AlertDialogCancel>cancel</AlertDialogCancel> <AlertDialogAction variant="danger" type="submit">delete</AlertDialogAction> </AlertDialogFooter> </form> </AlertDialog> </ItemActions> </Item> </ItemGroup> <Empty e:if={events.length === 0} title="no upcoming events" /> </main> </html>

The admin template adds a creation form at the top and a delete action per row. The form is three Fields; onSubmit calls events.insert(...) with their values converted to the column types (the datetime-local value is a string; new Date(...) turns it into the Date the column needs). Delete is an AlertDialog in each row's ItemActions. Its action is the submit button of a form inside the alert, so onDelete runs from that form's onsubmit only once the user confirms, and the click closes the dialog.

Both mutator calls run the LiveTable's handler before any SQL runs. A non-admin who somehow reaches the admin template (a stale session, a bug in the route guard) would still fail in the LiveTable's handler, where isUserAdminOrThrow() throws. The route and the handlers make the same check.

Routes

Register both routes in index.ts:

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

Notes

  • One LiveTable, two templates. Both pages open a view on the same LiveTable, and both views subscribe to the same broadcast channel, so an admin insert or delete appears on every public browser, on every app server, with no extra code.
  • Auth in two places. The admin route's isUserAdminOrThrow stops the page from rendering for a non-admin. The same call inside each handler stops the insert, update or delete. The route check keeps a non-admin from seeing the admin page; the handler check is the one that protects the rows.
  • Editing existing events. Add an update button per row that calls events.update({ ...event, title, description, eventDate }) and either a modal form or a separate /admin/events/:id route. The update handler is already gated on admin.
  • Past events. The custom select loads the initial rows. It does not filter the rows broadcast afterwards: when an admin inserts an event dated last week, the insert is broadcast and the event appears in every open list. To hide past events, filter in the template (events.filter((e) => +e.eventDate >= Date.now() - 3600000)). To let admins manage archived events, add an @rpc listPastEvents() that returns rows from sql, and render it in a separate "archived" section on the admin page. Past events don't need live sync.
  • Multiple admin actions. A "feature" toggle, a "highlight" flag, or any other per-event mutation is one more column on the table plus an update call. The update handler makes the same admin check whichever field changes.
  • Events imported from elsewhere. Add the trigger from elements man recipes live-from-sql and a job or psql session inserting into events goes live on every open list too.
  • Public read without LiveTable. If live updates on the public page aren't valuable (the events list barely changes), swap the view for an @rpc that returns rows from sql, or a plain sql call in the public route handler. The admin page keeps the LiveTable for the live add/delete UX. The two pages then read the table in different ways, and the admin page's insert and delete code does not change.
Prev Markdown BlogNext Cron Cache
Product
Manual Pricing Compare
Company
History Contact
Legal
Privacy Policy Acceptable Use Terms License Agreement
© Elements Dev Corporation 2026