Tutorial: a multi-user todo list

The smallest real multi-user app: everyone keeps their own todo list and nobody can read anyone else's, not from the page, not through the API. You will write one table, one access policy, two pages and a morning email of overdue items, check it as a member, verify it and put it on a link. About fifteen minutes.

What you will learn

  • A table whose rows belong to whoever writes them (default ctx.uid()).
  • Private rows with one row-level security policy, checked by Postgres on every read and write.
  • Pages that read and write with useQuery and useTable, and a sign-up page.
  • A scheduled workflow that emails each member their own items, dry-run before it sends anything.

1. Start the project

With an agent (Claude Code, Cursor, Codex or any MCP client connected to Appbricx):

Use appbricx. Create a project "Tick": a personal todo list, code-first.
Each member sees and edits only their own todos (title, notes, due date,
done). A todo needs a title. Every morning at 09:00 London time, email
each member their overdue todos. Check, apply, try it as a member,
dry-run the email, verify.

The agent calls create_project, then writes the files below with the code tool. By hand: create the project in the console (or have an agent call create_project), put the files below in a folder named tick, and push it with the CLI (step 3).

2. The files

Eight files. Everything else (the data API, the sign-in screen, the types of each row) comes from the platform.

app.config.ts

// app.config.ts: Tick's name, sign-up and its one role.
import { defineApp } from "@appbricx/define";

export default defineApp({
  brand: { name: "Tick", tagline: "Your list, nobody else's", color: "#2563EB" },
  locale: { language: "en-GB", timezone: "Europe/London" },
  auth: { signup: { as: ["member"] } },
  roles: {
    member: { kind: "consumer", label: "Member" },
  },
});

db/schema/todo.sql

-- db/schema/todo.sql: one row per todo, owned by the member who wrote it.
create table if not exists todo (
  id         uuid primary key default gen_random_uuid(),
  user_id    uuid not null default ctx.uid(),
  title      text not null,
  notes      text,
  due_on     date,
  done       boolean not null default false,
  created_at timestamptz not null default now(),
  constraint todo_has_title check (length(btrim(title)) > 0)
);
create index if not exists todo_user on todo (user_id);

db/access/todo.sql

-- db/access/todo.sql: each member reads and writes only their own todos.
drop policy if exists todo_own on todo;
create policy todo_own on todo for all
  using (user_id = (select ctx.uid()))
  with check (user_id = (select ctx.uid()));

routes/_layout.tsx

// routes/_layout.tsx: the header around every page.
import type { ReactNode } from "react";
import { Link, useAuth } from "@appbricx/ui";

export default function Layout({ children }: { children: ReactNode }) {
  const auth = useAuth();
  return (
    <div className="min-h-screen bg-stone-50 text-stone-900">
      <header className="flex items-center gap-4 border-b bg-white px-6 py-4">
        <Link to="/" className="font-semibold">Tick</Link>
        {auth.user ? (
          <button type="button" className="ml-auto" onClick={() => void auth.signOut()}>
            Sign out
          </button>
        ) : (
          <span className="ml-auto flex gap-4">
            <Link to="/signin">Sign in</Link>
            <Link to="/signup">Create an account</Link>
          </span>
        )}
      </header>
      {children}
    </div>
  );
}

routes/index.tsx

// routes/index.tsx: the signed-in member's own list (row-level security decides).
import { useState } from "react";
import { defineRoute, useQuery, useTable } from "@appbricx/ui";

export const meta = defineRoute({ roles: ["member"], title: "My todos" });

export default function Todos() {
  const { rows, loading } = useQuery("todo", { sort: "due_on" });
  const todos = useTable("todo");
  const [title, setTitle] = useState("");
  const [due, setDue] = useState("");
  const [error, setError] = useState("");

  const add = async () => {
    setError("");
    try {
      await todos.create({ title, due_on: due || null });
      setTitle("");
      setDue("");
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e)); // e.g. the todo_has_title check
    }
  };

  return (
    <main className="mx-auto max-w-xl p-6">
      <h1 className="mb-4 text-2xl font-bold">My todos</h1>
      <form className="mb-6 flex gap-2" onSubmit={(e) => { e.preventDefault(); void add(); }}>
        <label className="flex-1">
          <span className="sr-only">Title</span>
          <input className="w-full rounded border px-3 py-2" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="What needs doing?" />
        </label>
        <label>
          <span className="sr-only">Due</span>
          <input type="date" className="rounded border px-3 py-2" value={due} onChange={(e) => setDue(e.target.value)} />
        </label>
        <button type="submit" className="rounded bg-blue-600 px-4 py-2 text-white">Add</button>
      </form>
      {error ? <p role="alert" className="mb-4 text-red-700">{error}</p> : null}
      {loading ? <p>Loading…</p> : null}
      {!loading && rows.length === 0 ? <p className="text-stone-500">Nothing to do.</p> : null}
      <ul className="grid gap-2">
        {rows.map((t) => (
          <li key={t.id} className="flex items-center gap-3 rounded border bg-white px-3 py-2">
            <input type="checkbox" checked={t.done} aria-label={"Done: " + t.title} onChange={() => void todos.update(t.id, { done: !t.done })} />
            <span className={t.done ? "flex-1 text-stone-400 line-through" : "flex-1"}>{t.title}</span>
            {t.due_on ? <span className="text-sm text-stone-500">{t.due_on}</span> : null}
            <button type="button" className="text-sm text-stone-500" onClick={() => void todos.remove(t.id)}>
              Delete
            </button>
          </li>
        ))}
      </ul>
    </main>
  );
}

routes/signup.tsx

// routes/signup.tsx: a visitor creates a member account (/signin is built in).
import { useState } from "react";
import { defineRoute, useAuth, useNavigate } from "@appbricx/ui";

export const meta = defineRoute({ public: true, title: "Create your account" });

export default function SignUp() {
  const auth = useAuth();
  const navigate = useNavigate();
  const [form, setForm] = useState({ name: "", email: "", password: "" });
  const [error, setError] = useState("");
  const set = (k: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) => setForm({ ...form, [k]: e.target.value });

  const submit = async () => {
    setError("");
    try {
      await auth.signUp({ ...form, role: "member" });
      navigate("/");
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    }
  };

  return (
    <main className="mx-auto max-w-sm p-6">
      <h1 className="mb-4 text-2xl font-bold">Create your account</h1>
      <form className="grid gap-3" onSubmit={(e) => { e.preventDefault(); void submit(); }}>
        <label className="grid gap-1">Name<input className="rounded border px-3 py-2" value={form.name} onChange={set("name")} required /></label>
        <label className="grid gap-1">Email<input type="email" className="rounded border px-3 py-2" value={form.email} onChange={set("email")} required /></label>
        <label className="grid gap-1">Password<input type="password" className="rounded border px-3 py-2" value={form.password} onChange={set("password")} required /></label>
        <button type="submit" className="rounded bg-blue-600 px-4 py-2 text-white">Create account</button>
      </form>
      {error ? <p role="alert" className="mt-3 text-red-700">{error}</p> : null}
    </main>
  );
}

workflows/digest.ts

// workflows/digest.ts: every morning, each member gets their own overdue todos.
import { cron } from "@appbricx/workflows";

export const overdueDigest = cron("09:00", { tz: "Europe/London" }, async (_event, step) => {
  // A schedule runs as the app, so this reads every member's todos.
  const rows = await step.sql(
    "overdue",
    "select user_id, title, due_on::text as due_on from todo where not done and due_on < current_date order by user_id, due_on",
  );
  const byUser = new Map<string, string[]>();
  for (const r of rows) {
    const id = String(r.user_id);
    byUser.set(id, [...(byUser.get(id) ?? []), String(r.title) + " (due " + String(r.due_on) + ")"]);
  }
  let sent = 0;
  for (const [userId, items] of byUser) {
    const user = await step.run("account " + userId, () => step.ctx.users.get(userId));
    if (!user?.email) continue;
    await step.send.email("overdue-todos", {
      to: String(user.email),
      vars: { count: items.length, items: items.join("; "), link: step.url("/") },
    });
    sent++;
  }
  return { members: byUser.size, sent };
});

messages/email/overdue-todos.md

---
subject: "{{count}} overdue {{plural count \"todo\" \"todos\"}}"
preheader: What slipped past its due date.
vars:
  count: number
  items: string
  link: url
sample:
  count: 2
  items: "Book the dentist (due 2026-10-27); Renew passport (due 2026-10-20)"
  link: https://tick.example.com/
---
# Still on your list

{{items}}

[Open Tick]({{link}})

What each part does

  • user_id uuid not null default ctx.uid(): a new todo belongs to whoever inserts it. The page never sends a user id.
  • The policy todo_own: using limits which rows a member reads, changes and deletes; with check stops anyone writing a row for another member. A signed-out visitor has no user id, so the policy gives them nothing.
  • todo_has_title: a check constraint, so an empty title is refused for every caller. The page shows the refusal in its catch.
  • routes/index.tsx is for the member role. A signed-out visitor who opens it gets the built-in sign-in form; routes/signup.tsx is the sign-up form, because the built-in screen only signs people in.
  • workflows/digest.ts: a schedule runs as the app, so its step.sql reads every member's todos. It groups them by user_id, finds each account's email with step.ctx.users.get (recorded in step.run, so a retry doesn't ask again) and sends the template once per member.

3. Check and apply

An agent writes and checks one file at a time; errors come back with the file and line:

code { "project_id": "…", "action": "create", "kind": "table", "name": "todo",
       "content": "<db/schema/todo.sql>", "then": "check" }
code { "project_id": "…", "action": "create", "kind": "access", "name": "todo",
       "content": "<db/access/todo.sql>", "then": "check" }
…
code { "project_id": "…", "action": "list" }       // routes by URL, tables, policies, workflows
project_files { "project_id": "…", "action": "apply" }

By hand, from the folder that holds app.config.ts:

export APPBRICX_API=https://appbricx.com/api/dev/v1 APPBRICX_TOKEN=apx_pat_…
appbricx push <project-id> tick --check     # type-check, SQL lint, plan: nothing changes
appbricx push <project-id> tick --apply     # dev database migrated, pages built, workflow armed

The apply answer lists one demo sign-in per role (here, a member). Push sends the folder as the whole draft: a file that is in the project but not in the folder is deleted from the draft.

4. Try it as a member

Add a todo the way the page does, as the member demo sign-in:

call_app { "project_id": "…", "method": "POST", "path": "/__appbricx/api/v1/todo",
           "input": { "title": "Renew passport", "due_on": "2026-10-20" },
           "as": { "kind": "user", "role": "member" } }

call_app { "project_id": "…", "path": "/__appbricx/api/v1/todo" }     // signed out: no rows

Ask why a role is refused, without changing anything:

explain { "project_id": "…", "about": "access", "table": "todo", "op": "read", "as": "guest" }
// verdict denied, decided by row-level security, with the policy todo_own and why it doesn't pass

And look at the page as the member, with the steps a person would take:

screenshot { "project_id": "…", "route": "/", "as": "member",
             "steps": [{ "fill": { "label": "Title", "value": "Buy stamps" } },
                       { "click": "Add" }, { "wait": "Buy stamps" }] }

To see two members side by side, sign up a second account on /signup in the preview: its list starts empty, and the first member's todos never show up in it.

5. Dry-run the morning email

Don't wait for 09:00. A dry run runs the workflow once against the dev data and lists what it would do, with nothing sent or written. A workflow's id is its export name in lower case (workflows { "action": "list" } shows them):

workflows { "project_id": "…", "action": "dry_run", "id": "overduedigest" }
// effects: step.sql "overdue", then one email per member with overdue todos (not sent)

message_previews { "project_id": "…" }    // the overdue-todos email rendered with its sample

run { "action": "workflow", "id": "overduedigest" } runs it for real on dev. Emails from dev stay in the outbox (tail { "kind": "emails" }) unless they go to the project's owners and admins.

6. Verify and deploy

verify { "project_id": "…" }                     // every role against every table, then the pages in a browser
deploy { "project_id": "…", "subdomain": "tick" }   // verify again, snapshot, migrate production, publish

The deploy answer gives the live address. Look at the signed-out check in the report: it should list todo as closed to signed-out visitors.

Gotchas

  • Seeded todos belong to nobody. A seed runs as the database owner, where ctx.uid() is null, so this app has no seeds: create todos while signed in.
  • current_date is the database's date (UTC). The schedule fires at 09:00 London time, but "overdue" is decided in UTC. Compare with (now() at time zone 'Europe/London')::date if that matters to you.
  • Code between steps runs again after a retry: keep it deterministic and put lookups in step.run. See workflows.
  • Want to know when people sign up? The next tutorial adds a profile row per member and posts each one to Slack.

Related