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/ Team-Partitioned Table

Team-Partitioned Table

elements man recipes/team-partitioned-table

On This Page

  • Migration
  • Membership helpers
  • LiveTable
  • Home page
  • Team page
  • Routes
  • Notes

How to gate a LiveTable's partition by group membership instead of by URL secrecy. The membership check runs in two places. The route guard verifies the signed-in user belongs to the team before calling view({ teamId }) on the LiveTable. The LiveTable's insert, update, and delete handlers verify membership again on every mutation. A user removed from a team mid-session loses access on their next mutation, not their next page load.

The data is a tasks table with a teamId column and a teamMembers join table holding the user-to-team relationships. Opening the view on { teamId } also means each browser receives only its team's rows.

Migration

Terminal
elements create migration 'add teams and tasks' -tables=users,teams,teamMembers,tasks
app/migrations/<timestamp>-add-teams-and-tasks.migration.sql
-- add teams and tasks -- 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 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 ); create trigger usersTouchUpdatedAt before update on users for each row execute function touchUpdatedAt(); create table teams ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), name text not null ); create trigger teamsTouchUpdatedAt before update on teams for each row execute function touchUpdatedAt(); create table teamMembers ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), userId uuid not null references users(id) on delete cascade, teamId uuid not null references teams(id) on delete cascade, unique (userId, teamId) ); create trigger teamMembersTouchUpdatedAt before update on teamMembers for each row execute function touchUpdatedAt(); create table tasks ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), teamId uuid not null references teams(id) on delete cascade, title text not null, done boolean not null default false ); create index tasksTeamIdIdx on tasks (teamId); create trigger tasksTouchUpdatedAt before update on tasks for each row execute function touchUpdatedAt();

teamMembers is the many-to-many between users and teams. The unique (userId, teamId) constraint prevents duplicate memberships. tasksTeamIdIdx keeps per-team queries fast as the table grows. The on delete cascade on tasks.teamId cleans up tasks when a team is deleted.

Membership helpers

The / and /teams/:id pages both check membership and both read the tasks table, so these two modules are in app/shared/services/. If only one page used them, they would be in that page's template.ehtml.

app/shared/services/teams.ts
import { sql, session, ForbiddenError } from "@elements/app"; export function isTeamMember(userId: string, teamId: string): boolean { return !sql(` select 1 from teamMembers where userId = ${userId} and teamId = ${teamId} `).empty(); } export function isTeamMemberOrThrow(teamId: string) { session.isLoggedInOrThrow(); if (!isTeamMember(session.getOrThrow('userId'), teamId)) { throw new ForbiddenError("not a member of this team"); } }

isTeamMember returns whether the user is a member of the team. isTeamMemberOrThrow throws when the user is not, and is called by the route and by every handler on the LiveTable. It first calls session.isLoggedInOrThrow() so an unauthenticated request gets AuthError (401), then it reads the user id and throws ForbiddenError (403) if the signed-in user is not a member of the target team.

LiveTable

app/shared/services/tasks.ts
import { LiveTable } from "@elements/app"; import { isTeamMemberOrThrow } from "#app/shared/services/teams"; export interface Task { id: string; createdAt: Date; teamId: string; title: string; done: boolean; } export let tasks: LiveTable<Task> = new LiveTable<Task>({ insert: (item) => { isTeamMemberOrThrow(item.teamId!); return tasks.insert(item); }, update: (item) => { isTeamMemberOrThrow(item.teamId); return tasks.update(item); }, delete: (item) => { isTeamMemberOrThrow(item.teamId); return tasks.delete(item); }, });

The route below opens the table with view({ teamId }). The partition decides which rows each browser receives and fills the column on insert, so item.teamId is set by the time the insert handler runs (the ! says so to the type checker, since an insert payload is Partial<Task>). Every mutation is also checked against the partition the view was opened on; a browser cannot mutate a row in a team it does not hold a view for, regardless of the handler. The handlers add a second check: even with a view, isTeamMemberOrThrow runs on every mutation, so a member who is removed mid-session loses access on the next mutation rather than on the next page load. Each handler then calls tasks.insert, tasks.update or tasks.delete on the declaration, which is the auto-SQL: one statement against the table, with no handler. Because the initializer refers to tasks, the declaration needs an explicit LiveTable<Task> annotation.

Home page

Terminal
elements create page home

The home page shows the signed-in user's teams. Each team links to /teams/:id.

app/pages/home/index.ts
import { Request, Response, sql, session } from "@elements/app"; import home from "./template"; import { Team } from "./services"; export default function route(req: Request, res: Response) { session.isLoggedInOrThrow(); let teams = sql<Team>(` select t.id, t.name from teams t join teamMembers m on m.teamId = t.id where m.userId = ${session.getOrThrow('userId')} order by t.name `).all(); return new home({ teams }); }
app/pages/home/services.ts
export interface Team { id: string; name: string; }

The home page has no RPC; services.ts exists only to hold the shared Team interface so both index.ts and template.ehtml can import it without an index-template cycle.

app/pages/home/template.ehtml
import "./style.css"; import { Empty } from "@elements/ui/empty"; import { Team } from "./services"; <html class="page-home" (teams: Team[])> <main class="page-shell"> <h1>your teams</h1> <ul class="teams" e:if={teams.length > 0}> <li e:for={t of teams}> <a href={`/teams/${t.id}`}>{t.name}</a> </li> </ul> <Empty e:else title="no teams yet" description="ask an admin to add you to one." /> </main> </html>

A user with no memberships sees the Empty template in place of the list: a title and a line on what to do next.

Team page

Terminal
elements create page team

The team page loads the team's name from the database, opens the team's partition of tasks, and passes both to the template.

app/pages/team/index.ts
import { Request, Response, sql } from "@elements/app"; import team from "./template"; import { Team } from "./services"; import { isTeamMemberOrThrow } from "#app/shared/services/teams"; import { tasks } from "#app/shared/services/tasks"; export default function route(req: Request, res: Response) { let teamId = req.params.id; isTeamMemberOrThrow(teamId); let row = sql<Team>(` select id, name from teams where id = ${teamId} `).firstOrThrow("team not found"); return new team({ team: row, tasks: tasks.view({ teamId }), }); }
app/pages/team/services.ts
export interface Team { id: string; name: string; }
app/pages/team/template.ehtml
import "./style.css"; import { LiveView } from "@elements/app"; import { Button } from "@elements/ui/button"; import { Checkbox } from "@elements/ui/checkbox"; import { Icon } from "@elements/ui/icon"; import { Input } from "@elements/ui/input"; import { Task } from "#app/shared/services/tasks"; import { Team } from "./services"; function onSubmit(t: LiveView<Task>, draft: { value: string }) { t.insert({ title: draft.value, done: false, }, () => draft.value = ""); } function onToggle(t: LiveView<Task>, item: Task, done: boolean) { t.update({ ...item, done, }); } function onRemove(t: LiveView<Task>, item: Task) { t.delete(item); } <html class="page-team" ( team: Team, tasks: LiveView<Task>, private draft: { value: string } = { value: "" }, )> <main class="page-shell"> <h1>{team.name}</h1> <ul class="tasks"> <li e:for={item of tasks.sort((a, b) => +a.createdAt - +b.createdAt)} class={["row", item.done && "done"]}> <Checkbox checked={item.done} attrs={{ "aria-label": `Done: ${item.title}` }} onCheckedChange={(done) => onToggle(tasks, item, done)} /> <span class="text">{item.title}</span> <Button variant="ghost" size="sm" icon label={`Remove ${item.title}`} onclick={() => onRemove(tasks, item)}> <Icon name="x" /> </Button> </li> </ul> <form class="row" onsubmit={() => onSubmit(tasks, draft)}> <Input value={draft.value} placeholder="add a task" required /> <Button variant="primary" type="submit">add</Button> </form> </main> </html>

tasks.insert({ title, done: false }) does not pass teamId explicitly. The partition fills the column from the view, so the inserted row gets the correct team id automatically, and passing a different teamId would throw PartitionMismatchError.

Routes

Register the pages in index.ts:

index.ts
import home from "#app/pages/home"; import team from "#app/pages/team"; // ... app.route("/", home); app.route("/teams/:id", team);

Notes

  • Seeding users and teams. This recipe assumes signin and signup come from the authentication recipe, plus a way to create teams and assign membership. For development, run insert into teams (name) values ('engineering') and insert into teamMembers (userId, teamId) select id, (select id from teams where name='engineering') from users where handle='you' in psql. To have tasks inserted from psql appear live on open team pages, add the trigger from elements man recipes live-from-sql.
  • Cross-team data isolation. A user visits /teams/A and /teams/B as separate page loads. Each route opens a separate partition. Rows broadcast for team A are not sent to the user's view of team B.
  • Adding a per-task assignee. Add assigneeId uuid references users(id) to the tasks table; the auto-SQL includes the new column. The handlers still check team membership. To let only the assignee mark a task done, add that check inside the update handler.
  • Member roles. To distinguish admins from regular members, add a role column to teamMembers with an enum like the userRole pattern in elements man recipes admin-roles. The membership query checks the role: where userId = ... and teamId = ... and role = 'admin'.
Prev Shared ListsNext Chat Rooms
Product
Manual Pricing Compare
Company
History Contact
Legal
Privacy Policy Acceptable Use Terms License Agreement
© Elements Dev Corporation 2026