Skip to content
clientdb

Search the docs

Find a page or section

Get started

Public API overview

Every part of clientdb's public API in one example app: schema, permissions, sessions, the server, clients, reads, writes and operations.

This page walks through every part of the public API in one example app, from the schema to the deploy step. Each section links to the page that covers its part in depth.

The example app

Framecast is a screen recorder sold as a subscription. Its data:

  • users and teams, joined by team members with a role;
  • subscriptions (personal or for a team), each with licenses (seats), and the devices activated on each license;
  • payments and their refunds.

It has two web apps on one schema and one Postgres database, already managed with Prisma and served by tRPC:

  • the customer dashboard: a user's own devices, team, seats and billing history. Small, per user, kept on the device.
  • the admin panel: staff search every customer, open one, and issue refunds. Nothing is kept on disk, and only what staff opened is in memory.

Schema: models and relations

There are two ways to write the schema, and both give the same schema value to the rest of the app: in TypeScript, or derived from schema.prisma with fromPrisma. Framecast already has Prisma, so it uses the second. The TypeScript form comes first because it spells everything out.

In TypeScript

A model file imports nothing but @clientdb/schema, and other models are named as strings, so files can refer to each other in cycles.

src/sync/schema/accounts.ts
import { model, t } from "@clientdb/schema";

export const user = model(
  {
    email: t.string().unique(),
    name: t.string(),
    avatarUrl: t.string().nullable(),
  },
  { load: "eager" },
);

export const team = model(
  {
    name: t.string(),
    slug: t.string().unique(),
    createdBy: t.belongsTo("user", { inverse: "createdTeams" }),
    // recording defaults every member of the team may change
    background: t.string().default("gradient"),
    cursorSize: t.number().default(1),
    exportFormat: t.enum(["mp4", "gif", "webm"]).default("mp4"),
    exportQuality: t.enum(["standard", "high"]).default("standard"),
    watermark: t.boolean().default(false),
    updatedAt: t.timestamp().updatedAt(),
  },
  { load: "eager", archivable: true },
);

export const teamMember = model(
  {
    team: t.belongsTo("team", { inverse: "members", onDelete: "cascade" }),
    user: t.belongsTo("user", { inverse: "memberships", eager: true }),
    role: t.enum(["owner", "admin", "member"]).default("member"),
  },
  { load: "eager", indexes: [["teamId", "role"]] },
);
src/sync/schema/billing.ts
import { model, t } from "@clientdb/schema";

export const subscription = model(
  {
    id: t.uuid({ prefix: "sub" }).id(),
    customer: t.belongsTo("user", { inverse: "subscriptions", eager: true }),
    team: t.belongsTo("team", { inverse: "subscriptions" }).nullable(),
    plan: t.enum(["pro", "team", "education"]),
    interval: t.enum(["month", "year"]),
    status: t.enum(["trialing", "active", "canceling", "canceled", "pastDue"]),
    seats: t.number().default(1),
    renewsAt: t.timestamp().nullable(),
  },
  { load: "eager" },
);

export const license = model(
  {
    subscription: t.belongsTo("subscription", { inverse: "licenses", onDelete: "cascade", eager: true }),
    assignee: t.belongsTo("user", { inverse: "licenses" }).nullable(),
    /** The key people paste into the desktop app; only some viewers receive it. */
    key: t.string().unique().restricted(),
    maxDevices: t.number().default(2),
  },
  { load: "eager" },
);

export const device = model(
  {
    license: t.belongsTo("license", { inverse: "devices", onDelete: "cascade", eager: true }),
    user: t.belongsTo("user", { inverse: "devices" }),
    name: t.string(),
    platform: t.enum(["macos", "windows"]),
    lastSeenAt: t.timestamp(),
    details: t.json<{ appVersion: string; osVersion: string }>(),
  },
  { load: "eager" },
);

// lazy, the default: a customer's payments load with their subscription (eager: true), never on their own
export const payment = model({
  id: t.uuid({ prefix: "pay" }).id(),
  subscription: t.belongsTo("subscription", { inverse: "payments", eager: true }),
  invoiceNumber: t.number().generated(),
  amount: t.decimal(),
  currency: t.enum(["usd", "eur"]),
  status: t.enum(["paid", "partiallyRefunded", "refunded"]),
  paidAt: t.timestamp(),
});

export const refund = model({
  id: t.uuid({ prefix: "ref" }).id(),
  payment: t.belongsTo("payment", { inverse: "refunds", onDelete: "cascade", eager: true }),
  issuedBy: t.belongsTo("user", { inverse: "issuedRefunds" }),
  amount: t.decimal(),
  reason: t.string(),
  createdAt: t.timestamp().defaultNow(),
});

export const auditEntry = model(
  {
    actor: t.belongsTo("user", { inverse: "auditEntries" }),
    action: t.string(),
    targetId: t.string(),
    createdAt: t.timestamp().defaultNow(),
  },
  { serverOnly: true },
);
src/sync/schema/index.ts
import { createSchema, type InferSchema } from "@clientdb/schema";
import { team, teamMember, user } from "./accounts";
import { auditEntry, device, license, payment, refund, subscription } from "./billing";

const builtSchema = createSchema({ user, team, teamMember, subscription, license, device, payment, refund, auditEntry });

/** A named type, so editor hovers stay short. */
export interface Schema extends InferSchema<typeof builtSchema> {}
export const schema: Schema = builtSchema;
  • Models are named by their key in createSchema: teamMember, auditEntry.
  • assignee: t.belongsTo("user", …) adds the assigneeId column, the license.assignee relation and the user.licenses collection.
  • onDelete: "cascade": a license lives and dies with its subscription. Deleting the subscription deletes its licenses (and undo brings them back), and a license counts as archived while its subscription is. Who may read a license is up to its read rule, like any other model's.
  • Without onDelete, a nullable relation is set to null when its target is deleted ("setNull"), and a required one blocks the delete ("restrict").
  • archivable: true adds archivedAt and archivedBy, and team.archive(): an archived team is hidden on every device, with its members, and kept in the database.
  • serverOnly models stay on the server: rules can use them, clients get no API for them.
  • The viewer model, whose rows are the signed-in users, is user unless createSchema(models, { viewer: "member" }) names another.

Fields and their options

Field or optionMeaning
t.string(), t.number(), t.boolean(), t.enum([…]), t.json<T>()the basic types; .nullable(), .default(value) and .indexed() work on each
t.timestamp()a time, as milliseconds since 1970 on clients (a number, not a Date); .defaultNow() and .updatedAt() fill it in
no id fieldevery model gets id, a UUIDv7 generated on the device that creates the row
.id()this field is the id instead, and it must be named id. t.uuid({ prefix: "pay" }).id() makes ids such as pay_01932c… on every client, matching the ids your Prisma code creates. A prefix is letters and digits, starting with a letter
.unique()the field identifies one row, so a lazy read by it (where({ email })) loads that row
.restricted()only viewers allowed by the field's own read rule receive its value; for everyone else it is undefined on the client
t.decimal()exact decimals (Prisma Decimal), sent and typed as strings such as "49.00"; never a float
.generated()Postgres fills it in (a sequence, a default, a trigger); clients read it but never send it

See Schema in TypeScript for every option.

With Prisma: fromPrisma

Framecast's schema.prisma already describes every model, field and relation. fromPrisma reads it through the generator and takes only what Prisma can't say: which models load eagerly, which relations are eager, which fields are restricted, and what stays on the server:

src/sync/schema.ts
import { fromPrisma } from "@clientdb/prisma";
import { prismaModels } from "@/generated/clientdb";

export const schema = fromPrisma(prismaModels, {
  serverOnly: ["AuditEntry"],
  omit: { Payment: ["stripePaymentIntentId"] }, // never leaves the server
  models: {
    User: { load: "eager" },
    Team: { load: "eager", archivable: true },
    TeamMember: {
      load: "eager",
      relations: { user: { eager: true } },
    },
    Subscription: {
      load: "eager",
      id: { prefix: "sub" },
      relations: { customer: { eager: true } },
    },
    License: {
      load: "eager",
      restricted: ["key"],
      relations: { subscription: { eager: true } },
    },
    Device: {
      load: "eager",
      relations: { license: { eager: true } },
    },
    Payment: {
      id: { prefix: "pay" },
      relations: { subscription: { eager: true } },
    },
    Refund: {
      id: { prefix: "ref" },
      relations: { payment: { eager: true } },
    },
  },
});
export type Schema = typeof schema;
  • models is keyed by Prisma model name. A model you don't list syncs lazily, with no extra options.
  • Model names, fields and relations are checked against your Prisma models: models: { Licence: … }, or Licence as a key of omit or notSecret, is a type error on that key, and fromPrisma throws naming it. Options written apart from the call are checked too with satisfies FromPrismaOptions<typeof prismaModels>.
  • relations takes the relation fields that hold the foreign key (TeamMember.user); its one option is eager. Putting one on the list side (User.memberships) is a type error, just as belongsTo only goes on the child.
  • Inverse names, onDelete, @unique, Decimal and @default(autoincrement()) come from schema.prisma, so they aren't repeated here. License.subscription says onDelete: Cascade there, so licenses are deleted with their subscription on devices too, exactly as onDelete: "cascade" does in the TypeScript schema; SetNull clears the key, and every other action restricts.
  • archivable: true stores archives in the model's own archivedAt DateTime? and archivedBy String? columns. Framecast's Team has both; on a model without them, archivable is a type error that names the missing columns.
  • A column whose name looks secret (token, secret, hash, password, salt, key) must be in omit, restricted or notSecret, so a new apiToken column can't reach browsers by accident. License.key passes because it's restricted.

See Prisma for the mapping.

Load modes

loadRows arrive
"lazy" (default)when something reads them: a relation (subscription.payments), a unique field (where({ email })), an id (get(id)), or the whole model (db.payment.all)
"eager"when the client starts: every row of the model the session may read

A lazy read returns what's on the device at once, and its status says whether more is on the way. DatabaseProvider renders once the eager models have arrived.

Eager is opt-in for models that stay small per user. If a session may read 100,000 rows of an eager model, all of them load at startup, so the engine warns:

Text
clientdb: a bootstrap for viewer 01932c… sent 48,210 eager rows (user: 47,996). Make large models lazy, or raise bootstrapRowWarning.

The default limit is 20,000 rows per bootstrap; createEngine({ bootstrapRowWarning: 50_000 }) raises it, and false turns the warning off.

Eager relations

eager: true on a belongsTo means: whenever a parent row arrives on a device, its children come with it, however the parent arrived. In the admin panel, a search that finds five customers brings each one's memberships, subscriptions, licenses, devices, payments and refunds in the same response. Opening one of them needs no further request.

The cascade has fixed limits, so loading one user can't pull in a whole team:

  • It only goes down, from a parent to the children marked eager: true, and on from those.
  • The rows those children point at (a membership's team) come along as single rows, and nothing cascades from them.
  • It stops at a model it already passed through, and at 5,000 rows per load (createEngine({ cascadeRowLimit })). What a cut cascade didn't deliver loads when it's read.

In the customer dashboard, subscriptions are eager, so their payments arrive at startup too: a few dozen rows per customer.

Prisma: tables, triggers and your existing writes

Prisma owns the tables and their migrations:

prisma/schema.prisma
generator clientdb {
  provider = "clientdb-prisma"
  output   = "../src/generated/clientdb"
}

model Payment {
  id                    String        @id @default(dbgenerated("'pay_' || uuidv7()")) // uuidv7() needs Postgres 18
  subscriptionId        String
  subscription          Subscription  @relation(fields: [subscriptionId], references: [id])
  invoiceNumber         Int           @default(autoincrement())
  amount                Decimal       @db.Decimal(10, 2)
  currency              Currency
  status                PaymentStatus
  paidAt                DateTime
  stripePaymentIntentId String        @unique
  refunds               Refund[]

  @@index([subscriptionId])
}
Terminal
npx clientdb-prisma models >> prisma/schema.prisma   # clientdb's bookkeeping tables, as Prisma models
npx prisma migrate dev --name clientdb
npx clientdb-prisma triggers src/sync/schema.ts > prisma/migrations/20261202_clientdb_triggers/migration.sql
npx prisma migrate dev

triggers <module> prints the capture triggers for every model the schema maps, serverOnly ones included (rules read them), and drops the triggers of tables that no longer sync. Run it again when you add or remove a model.

With the triggers installed, there is nothing to call. Every write to a synced table reaches the devices that may see it: Prisma Client in your tRPC routes, server actions, webhooks, raw SQL, other services.

Only if you can't or don't install the triggers, tell the engine which rows you wrote. Model names are typed:

src/server/afterWrite.ts
import { engine } from "@/sync/engine";

// only without the triggers
export async function afterRefund(paymentId: string, refundId: string) {
  await engine.changed({ payment: [paymentId], refund: [refundId] });
}

See Writes from your server.

Claims

A claim is a fact about the signed-in session that isn't a row, such as "this person has an active staff login". Declare each claim once, in a file both server and client import:

src/sync/claims.ts
import { declareClaim } from "@clientdb/schema";

export const $staff = declareClaim("staff");

Your session callback grants it, rules check it, and the client can ask for it. All three use the same typed value, so a misspelled claim is a compile error. Claims are yes-or-no.

Permissions

One file per area. A rule receives the row and $, the permission helpers. A claim works anywhere a condition does: in $.anyOf, $.and and $.or.

src/sync/permissions/accounts.ts
import { defineModelRules, defineRule } from "@clientdb/server";
import { $staff } from "../claims";
import { schema } from "../schema";

export const isTeamMember = defineRule(schema, "team", (team, $) => {
  return team.members.some((member) => {
    return member.userId.is($.viewer.id);
  });
});

export const isTeamAdmin = defineRule(
  schema,
  "team",
  (team, $) => {
    return team.members.some((member) => {
      return $.and(member.userId.is($.viewer.id), member.role.in(["owner", "admin"]));
    });
  },
  { name: "team.admin" },
);

export const userRules = defineModelRules(schema, "user", {
  read: (user, $) => {
    return $.anyOf({
      self: user.id.is($.viewer.id),
      teammate: user.memberships.some((membership) => {
        return isTeamMember(membership.team);
      }),
      staff: $staff,
    });
  },
  update: {
    when: (user, $) => {
      return user.id.is($.viewer.id);
    },
    fields: ["name", "avatarUrl"],
  },
  // what server queries (`adminDb.user.query`) may filter on, and the largest page
  query: {
    fields: { email: ["is", "contains", "endsWith"], name: ["contains"] },
    maxLimit: 100,
  },
});

export const teamRules = defineModelRules(schema, "team", {
  read: (team, $) => {
    return $.or(isTeamMember(team), $staff);
  },
  create: {
    when: (team, $) => {
      return $.authenticated;
    },
    enforce: ($) => ({ createdById: $.viewer.id }),
  },
  update: [
    {
      fields: ["background", "cursorSize", "exportFormat", "exportQuality", "watermark"],
      when: (team) => {
        return isTeamMember(team);
      },
    },
    {
      fields: ["name", "slug"],
      when: (team) => {
        return isTeamAdmin(team);
      },
    },
  ],
  archive: {
    when: (team, $) => {
      return team.createdById.is($.viewer.id);
    },
  },
});

// a member reads exactly like their team
export const teamMemberRules = defineModelRules(schema, "teamMember", {
  read: (member, $) => {
    return $.canRead(member.team);
  },
  create: {
    when: (member, $) => {
      return $.anyOf({
        admin: isTeamAdmin(member.team),
        founder: [member.team.createdById.is($.viewer.id), member.userId.is($.viewer.id)],
      });
    },
  },
  update: {
    when: (member) => {
      return isTeamAdmin(member.team);
    },
    fields: ["role"],
  },
});

update takes a list of field groups, each with its own condition. An update passes when every field it changes belongs to a group whose when holds, before and after the change. A member who changes watermark and name together is refused, and the error names name. One group, update: { when, fields }, needs no list.

src/sync/permissions/billing.ts
import { defineModelRules, defineRule } from "@clientdb/server";
import { $staff } from "../claims";
import { schema } from "../schema";
import { isTeamAdmin } from "./accounts";

export const canManageBilling = defineRule(schema, "subscription", (subscription, $) => {
  return $.anyOf({
    customer: subscription.customerId.is($.viewer.id),
    teamAdmin: isTeamAdmin(subscription.team),
  });
});

export const subscriptionRules = defineModelRules(schema, "subscription", {
  read: (subscription, $) => {
    return $.or(canManageBilling(subscription), $staff);
  },
});

export const licenseRules = defineModelRules(schema, "license", {
  read: {
    when: (license, $) => {
      return $.anyOf({ subscription: $.canRead(license.subscription), assignee: license.assigneeId.is($.viewer.id) });
    },
    fields: {
      // a team admin sees the seat, not its key
      key: (license, $) => {
        return $.anyOf({
          customer: license.subscription.customerId.is($.viewer.id),
          assignee: license.assigneeId.is($.viewer.id),
          staff: $staff,
        });
      },
    },
  },
  update: {
    when: (license) => {
      return canManageBilling(license.subscription);
    },
    fields: ["assigneeId"],
  },
});

export const deviceRules = defineModelRules(schema, "device", {
  read: (device, $) => {
    return $.canRead(device.license);
  },
  update: {
    when: (device, $) => {
      return device.userId.is($.viewer.id);
    },
    fields: ["name"],
  },
  delete: {
    when: (device, $) => {
      return $.anyOf({ owner: device.userId.is($.viewer.id), billing: canManageBilling(device.license.subscription) });
    },
  },
});

// no write rules: payments and refunds only change through your backend
export const paymentRules = defineModelRules(schema, "payment", {
  read: (payment, $) => {
    return $.canRead(payment.subscription);
  },
});

export const refundRules = defineModelRules(schema, "refund", {
  read: (refund, $) => {
    return $.canRead(refund.payment);
  },
});
  • read: { when, fields } is the form for a model with restricted fields: the row reaches a viewer when when holds, and each restricted field only when its own rule holds too. Every restricted field needs a rule, and only restricted fields take one.
  • A restricted field can't be used in query.fields: a server query could otherwise reveal it.
  • $.canRead(license.subscription) holds when the viewer may read the related row under its own model's read rule. It works in write rules too, and $.canRead(row, { except: ["staff"] }) leaves out labeled branches of that rule. A read rule that is exactly $.canRead(parent), like the member, device, payment and refund rules here, gives rows their parent's access, and when that access changes they are re-tagged in bulk.
  • Every synced model needs a read rule, onDelete: "cascade" children included: nothing is readable implicitly, and outside production a model without one is an error at startup.
src/sync/permissions/index.ts
import { definePermissions } from "@clientdb/server";
import { schema } from "../schema";
import * as accountRules from "./accounts";
import * as billingRules from "./billing";

export const permissions = definePermissions(schema, { ...accountRules, ...billingRules });

See Permissions.

The signed-in session

Your server says who is signed in; the browser never does:

src/sync/session.ts
import type { SyncSession } from "@clientdb/server";
import { auth } from "@/lib/auth";
import { getStaffLogin } from "@/lib/staff";
import { $staff } from "./claims";

export async function getSyncSession(request: Request, options: { asStaff: boolean }): Promise<SyncSession | null> {
  const session = await auth.api.getSession({ headers: request.headers });
  if (!session) {
    return null;
  }
  const staffLogin = options.asStaff ? await getStaffLogin(session.user.id) : null; // a separate two-day login
  return {
    viewer: session.user.id,
    claims: [$staff(staffLogin !== null)], // granted only when the argument is true (the default)
    readOnly: session.user.suspendedAt !== null, // may read, may not write
  };
}

Only the admin route asks for $staff (see Server setup). A staff member opening the customer dashboard is an ordinary customer there, so its eager models don't load every customer they could read as staff.

clientdb calls the session callback on every HTTP request, and on a live WebSocket each time its sync token renews (every 5 minutes by default, tokens.ttlSeconds). So when the two-day staff login ends, the next check finds no $staff, and the server removes from that device every row it could read only as staff. Nothing else to set up: a claim lasts as long as your callback keeps granting it.

On the client, db.$viewer is the signed-in user's row, and db.$session holds what the server verified: viewerId, claims, readOnly and hasClaim(claim).

src/app/admin/session.ts
import { adminDb } from "@/sync/adminDb";
import { $staff } from "@/sync/claims";

export function canIssueRefunds() {
  return adminDb.$session.hasClaim($staff);
}

export async function signOut() {
  await adminDb.$clear(); // drops every row and unsent change from memory and disk
}

A readOnly session can still read and query. The server refuses its writes, and the client refuses them before they show on screen: they throw a ReadOnlyError.

Server setup

Next.js

src/sync/engine.ts
import { createEngine } from "@clientdb/server";
import { hooks } from "./hooks";
import { permissions } from "./permissions";

export const engine = createEngine({
  permissions,
  hooks,
  retention: { log: "30d", archived: "90d" },
});

The routes and the live server sign short-lived sync tokens with one secret. Read it once, so a missing variable fails at startup:

src/sync/tokens.ts
import type { SyncTokenOptions } from "@clientdb/server";

const secret = process.env.CLIENTDB_SECRET;
if (!secret) {
  throw new Error("CLIENTDB_SECRET is not set");
}

export const syncTokens: SyncTokenOptions = { secret };
src/app/api/sync/[...path]/route.ts
import { clientdbHandler } from "@clientdb/server/next";
import { engine } from "@/sync/engine";
import { getSyncSession } from "@/sync/session";
import { syncTokens } from "@/sync/tokens";

export const { GET, POST } = clientdbHandler(engine, {
  session: (request) => {
    return getSyncSession(request, { asStaff: false });
  },
  tokens: syncTokens, // adds GET …/token, for the live server below
});
src/app/api/admin/sync/[...path]/route.ts
import { clientdbHandler } from "@clientdb/server/next";
import { engine } from "@/sync/engine";
import { getSyncSession } from "@/sync/session";

export const { GET, POST } = clientdbHandler(engine, {
  session: (request) => {
    return getSyncSession(request, { asStaff: true });
  },
  readOnly: true, // every session on this route is read-only
});

Node.js and live updates

HTTP is the default transport: clients pull on load, on focus, after writes and every 30 seconds. The customer dashboard also wants devices to appear the moment the desktop app activates one, so a small Node server holds the WebSockets:

server/live.ts
import express from "express";
import { createSyncServer } from "@clientdb/server";
import { engine } from "../src/sync/engine";
import { syncTokens } from "../src/sync/tokens";

// no session callback: the tokens carry the session and its claims
const syncServer = createSyncServer(engine, {
  tokens: syncTokens,
  cors: { origin: ["https://framecast.app"] },
});

const app = express();
app.use(syncServer.middleware);

const server = app.listen(4000);
syncServer.attachWebSocket(server);

process.on("SIGTERM", async () => {
  await syncServer.close();
  server.close();
  await engine.close();
});

See HTTP, Node.js servers and Live updates.

Clients

src/sync/dashboardDb.ts
"use client";
import { createDatabaseClient, indexedDb } from "@clientdb/client";
import { schema } from "./schema";

export const dashboardDb = createDatabaseClient({
  schema,
  storage: indexedDb(), // opens instantly next time, works offline
  live: { url: "wss://live.framecast.app/api/sync" },
});
src/sync/adminDb.ts
"use client";
import { createDatabaseClient } from "@clientdb/client";
import { mobxReactivity } from "@clientdb/mobx";
import { schema } from "./schema";

// no `storage`: nothing reaches the disk
export const adminDb = createDatabaseClient({
  schema,
  url: "/api/admin/sync",
  load: "lazy", // no eager bootstrap: staff may read every customer, but only load what they open
  readOnly: true, // no create, update or delete in its types
  eviction: { maxRows: 50_000 }, // forgets the customers opened longest ago
  reactivity: mobxReactivity(),
});

Eviction removes whatever one load brought in (one customer and their eager children) as a whole. Every collection that held those rows reads as "partial" again, so nothing reads as complete while part of it is gone, and the next read loads it again. What the app still observes stays: a collection or server query on screen, an entity read with get(id), and any row whose fields a component reads, with the loads that brought it.

src/sync/types.ts
import type { EntitiesOf, ReadOnlyEntity } from "@clientdb/client";
import type { Schema } from "./schema";

/** `DB["License"]` is a license with its fields and relations. */
export type DB = EntitiesOf<Schema>;

/** The admin panel's entities: fields and relations, no writes. */
export type AdminPayment = ReadOnlyEntity<DB["Payment"]>;

A restricted field is typed T | undefined for everyone: license.key is undefined on a team admin's device.

Reading in React: the customer dashboard

Reads are synchronous: the rows are already on the device.

src/app/dashboard/DevicesPage.tsx
"use client";
import { live, useLive } from "@clientdb/react";
import { dashboardDb } from "@/sync/dashboardDb";
import type { DB } from "@/sync/types";

const DeviceRow = live(({ device }: { device: DB["Device"] }) => {
  const lastSeen = new Date(device.lastSeenAt).toLocaleDateString(); // timestamps are milliseconds
  return (
    <li>
      {device.name} · {device.license.subscription.plan} · seen {lastSeen}
      <button
        onClick={() => {
          device.delete(); // gone at once; comes back if the server refuses
        }}
      >
        Deactivate
      </button>
    </li>
  );
});

export function DevicesPage() {
  const devices = useLive(() => {
    return dashboardDb.$viewer?.devices.orderBy("lastSeenAt", "desc").all ?? [];
  });
  return (
    <ul>
      {devices.map((device) => {
        return <DeviceRow key={device.id} device={device} />;
      })}
    </ul>
  );
}
src/app/dashboard/BillingHistory.tsx
"use client";
import { live } from "@clientdb/react";
import type { DB } from "@/sync/types";

export const BillingHistory = live(({ subscription }: { subscription: DB["Subscription"] }) => {
  const startOfYear = new Date(new Date().getFullYear(), 0, 1).getTime();
  const payments = subscription.payments.where({ paidAt: { gte: startOfYear } }).orderBy("paidAt", "desc").all;
  return payments.map((payment) => {
    return (
      <p key={payment.id}>
        #{payment.invoiceNumber} · {payment.amount} {payment.currency} · {payment.status}
      </p>
    );
  });
});

See Reading data and React.

Reading with MobX: search and the customer page

where filters what's on the device, and on a lazy model loads by a relation or a unique field. query asks the server, and merges its answer with what's already here:

src/app/admin/CustomerSearch.tsx
"use client";
import { observer } from "mobx-react-lite";
import Link from "next/link";
import { ProgressBar } from "@/components/ProgressBar";
import { adminDb } from "@/sync/adminDb";

export const CustomerSearch = observer(function CustomerSearch({ text }: { text: string }) {
  const results = adminDb.user.query({
    where: { email: { contains: text, mode: "insensitive" } },
    orderBy: ["email", "asc"],
    limit: 50,
  });

  return (
    <section>
      {results.status !== "complete" && <ProgressBar />}
      {results.all.map((customer) => {
        return (
          <Link
            key={customer.id}
            href={`/admin/customers/${encodeURIComponent(customer.email)}`}
            onMouseEnter={() => {
              adminDb.user.where({ email: customer.email }).preload();
            }}
          >
            {customer.email} · {customer.subscriptions.count} subscriptions
          </Link>
        );
      })}
      {results.hasMore && (
        <button
          onClick={() => {
            results.loadMore();
          }}
        >
          More
        </button>
      )}
    </section>
  );
});
results.statusMeaning
"loading"the server hasn't answered, and nothing on the device matches yet
"partial"the server hasn't answered; customers already on the device that match are shown
"complete"the server answered; from then on the result stays live, and results.refresh() asks again

where in a server query takes values, lists, ranges (gt, gte, lt, lte) and the text operators contains, startsWith and endsWith, with mode: "insensitive". The model's query rules on the server say which fields and operators are allowed.

Each search result arrives with its eager children, so customer.subscriptions.count is right at once, and opening a customer needs no further request. A customer opened from a link loads by their unique email, with the same cascade:

src/app/admin/customers/[email]/CustomerPage.tsx
"use client";
import { observer } from "mobx-react-lite";
import { Spinner } from "@/components/Spinner";
import { adminDb } from "@/sync/adminDb";
import { PaymentRow } from "./PaymentRow";

export const CustomerPage = observer(function CustomerPage({ email }: { email: string }) {
  const customerQuery = adminDb.user.where({ email });
  const customer = customerQuery.first;

  if (!customer) {
    return customerQuery.status === "complete" ? <p>No customer with this email</p> : <Spinner />;
  }
  return (
    <article>
      <h1>{customer.name}</h1>
      {customer.subscriptions.all.map((subscription) => {
        return (
          <section key={subscription.id}>
            <h2>
              {subscription.plan} · {subscription.status} · {subscription.licenses.count} seats
            </h2>
            {subscription.payments.all.map((payment) => {
              return <PaymentRow key={payment.id} payment={payment} />;
            })}
          </section>
        );
      })}
    </article>
  );
});

Writes and transactions

Every write shows on screen at once, then the server checks it against the rules. A refused write is undone on screen.

src/app/dashboard/team/teamActions.ts
import { dashboardDb } from "@/sync/dashboardDb";
import type { DB } from "@/sync/types";

// two creates, one atomic server transaction
export async function createTeam(name: string, slug: string) {
  const viewer = dashboardDb.$viewer;
  if (!viewer) {
    throw new Error("Not signed in");
  }
  const handle = dashboardDb.$transaction(() => {
    const team = dashboardDb.team.create({ name, slug, createdById: viewer.id });
    dashboardDb.teamMember.create({ teamId: team.id, userId: viewer.id, role: "owner" });
  });
  await handle.confirmed; // rejects with a TransactionError if the server refuses
}

export function assignSeat(license: DB["License"], memberId: string) {
  license.update({ assigneeId: memberId });
}

// the team settings form edits a draft: shown at once, sent only on save
export function editExportFormat(team: DB["Team"], exportFormat: DB["Team"]["exportFormat"]) {
  team.exportFormat = exportFormat;
}

export function saveTeamSettings(team: DB["Team"]) {
  team.save();
}

export function discardTeamSettings(team: DB["Team"]) {
  team.revert();
}

export function archiveTeam(team: DB["Team"]) {
  team.archive(); // hidden on every device with its members, kept in the database; team.unarchive() brings it back
}

export function undoLastChange() {
  dashboardDb.$undo(); // leaves alone fields someone else changed since
}
  • Ids are generated on the device, with the model's prefix: dashboardDb.subscription.create(…) makes a sub_… id. Generated fields such as invoiceNumber can't be written.
  • createdById: viewer.id is required: enforce only checks that it's the viewer, it never fills it in.

See Writing data and Transactions and undo.

Side effects: refunds through your own backend

clientdb doesn't run your business logic. A refund stays an ordinary tRPC mutation: it checks who's asking, calls Stripe with an idempotency key, and writes with Prisma. The triggers take it from there.

src/server/routers/billing.ts
import { z } from "zod";
import { toCents } from "@/lib/money";
import { prisma } from "@/lib/prisma";
import { stripe } from "@/lib/stripe";
import { router, staffProcedure } from "../trpc";

export const billingRouter = router({
  refundPayment: staffProcedure
    .input(
      z.object({
        paymentId: z.string(),
        amount: z.string(),
        reason: z.string().min(3),
        idempotencyKey: z.string().uuid(),
      }),
    )
    .mutation(async ({ input, ctx }) => {
      const payment = await prisma.payment.findUniqueOrThrow({ where: { id: input.paymentId } });
      const stripeRefund = await stripe.refunds.create(
        { payment_intent: payment.stripePaymentIntentId, amount: toCents(input.amount) },
        { idempotencyKey: input.idempotencyKey }, // a repeat with the same key refunds once
      );
      const isFullRefund = payment.amount.equals(input.amount);
      await prisma.$transaction([
        prisma.refund.create({
          data: { paymentId: payment.id, issuedById: ctx.user.id, amount: input.amount, reason: input.reason },
        }),
        prisma.payment.update({
          where: { id: payment.id },
          data: { status: isFullRefund ? "refunded" : "partiallyRefunded" },
        }),
      ]);
      return { stripeRefundId: stripeRefund.id };
    }),
});

On the client, $action runs the call, then waits for a sync that started after it returned, so the toast never shows next to the old status. If only that sync fails, it still resolves with your result, and the sync retries in the background:

src/app/admin/customers/[email]/issueRefund.ts
import { toast } from "@/components/toast";
import { trpc } from "@/lib/trpc";
import { adminDb } from "@/sync/adminDb";
import type { AdminPayment } from "@/sync/types";

// the refund dialog creates `idempotencyKey` when it opens, so a double submit refunds once
export async function issueRefund(payment: AdminPayment, amount: string, reason: string, idempotencyKey: string) {
  try {
    const { stripeRefundId } = await adminDb.$action(() => {
      return trpc.billing.refundPayment.mutate({ paymentId: payment.id, amount, reason, idempotencyKey });
    });
    toast.success(`Refunded (${stripeRefundId})`); // the refund row and the new payment status are on screen
  } catch (error) {
    toast.error(String(error));
  }
}

An $action can also show its outcome before the server answers. The writes inside optimistic change rows on this device only: never sent, stored or undoable. They're undone if the call fails, and replaced by the real rows when they arrive:

src/app/dashboard/billing/cancel.ts
import { trpc } from "@/lib/trpc";
import { dashboardDb } from "@/sync/dashboardDb";
import type { DB } from "@/sync/types";

export function cancel(subscription: DB["Subscription"]) {
  return dashboardDb.$action(
    () => {
      return trpc.billing.cancelSubscription.mutate({ subscriptionId: subscription.id });
    },
    {
      optimistic: () => {
        subscription.update({ status: "canceling" });
      },
    },
  );
}

optimistic receives the client with its write methods, so a read-only client such as the admin panel can preview too: optimistic: (db) => { db.payment.get(payment.id)?.update({ status: "refunded" }); }.

Sync status

src/app/dashboard/Providers.tsx
"use client";
import type { ReactNode } from "react";
import { DatabaseProvider, useLive, useTransactionErrors } from "@clientdb/react";
import { Spinner } from "@/components/Spinner";
import { toast } from "@/components/toast";
import { dashboardDb } from "@/sync/dashboardDb";

function SyncIndicator() {
  const status = useLive(() => {
    return dashboardDb.$status; // "bootstrapping" | "online" | "offline" | "outdated" | …
  });
  const pendingCount = useLive(() => {
    return dashboardDb.$pendingCount;
  });
  useTransactionErrors((rejection) => {
    toast.error(rejection.message);
  });

  if (status === "outdated") {
    return (
      <button
        onClick={() => {
          location.reload();
        }}
      >
        New version available: reload
      </button>
    );
  }
  if (status === "offline") {
    return <span>Offline</span>;
  }
  return <span>{pendingCount > 0 ? "Saving…" : "Saved"}</span>;
}

export function Providers({ children }: { children: ReactNode }) {
  return (
    <DatabaseProvider db={dashboardDb} ready fallback={<Spinner />}>
      <SyncIndicator />
      {children}
    </DatabaseProvider>
  );
}

ready shows the fallback until the eager models are usable, from IndexedDB or the network. A failed first load retries instead of failing; $ready() rejects only when the client is outdated or the server refuses the session.

src/app/dashboard/refresh.ts
import { dashboardDb } from "@/sync/dashboardDb";

export async function refreshNow() {
  await dashboardDb.$sync(); // includes everything the server committed before this call
}

Operations: hooks, retention and migrations

Hooks get who did what and the outcome, never row data, so they are safe to log:

src/sync/hooks.ts
import type { EngineHooks } from "@clientdb/server";
import { logger } from "@/lib/logger";

export const hooks: EngineHooks = {
  onWriteRejected: ({ session, code, model, operation, failedBranches }) => {
    logger.warn("write rejected", { viewer: session.viewer, code, model, operation, failedBranches });
  },
  onAccessRemoved: ({ session, groups, reason }) => {
    // reason: "claim" (the session callback stopped granting one) or "rules" (a write changed what the viewer may read)
    logger.info("access removed", { viewer: session.viewer, groups, reason });
  },
};

retention on the engine (see Server setup) prunes the sync log after 30 days; the shortest allowed is "1h". A client last synced before the oldest kept entry loads afresh, keeping its unsent changes. The ids of applied transactions are kept for retention.transactions (by default the longer of log and 90 days), so a resend never applies twice: after that, a resend the server may have applied is rejected with Stale. archived: "90d" deletes teams archived for more than 90 days, with their members, and the deletes reach every device (see Archive and delete). Pruning runs on every clientdb migrate, hourly in a process that called engine.start(), and whenever you call engine.prune().

Terminal
# deploy step, after Prisma's own migrations
npx prisma migrate deploy
npx clientdb migrate src/sync/engine.ts --dry-run   # prints what it would change, and changes nothing
npx clientdb migrate src/sync/engine.ts

Until clientdb migrate has run for the current schema and rules, the sync routes answer 503 NotMigrated. Clients on an older schema see $status === "outdated" and reload. See Migrations.