# What is clientdb? > A data layer that makes your app feel instant, and lets you delete most of your API code. clientdb keeps each user's data **in their browser**, and keeps it **in sync with your Postgres**. That one idea changes how you build an app: - **Your UI reads data like local variables.** The data is already on the device, so there's nothing to fetch and no spinner per component. Lists, filters and counts are instant, even with 100,000 items. You choose which data loads up front; the rest arrives the first time something reads it. - **Your UI writes data like local variables.** A change shows on screen immediately and is saved in the background. Undo comes for free. - **Your backend shrinks to one file.** Instead of an API route for every read and write, you describe who may see and change what, once. clientdb enforces it on the server for every request. - **Everyone stays up to date.** When someone changes something, everyone else who can see it gets the change, in every open tab and device. When someone loses access, the data disappears from their devices too. ```tsx title="A component, start to finish" import { live, useLive } from "@clientdb/react"; import { db, type Todo } from "@/sync/db"; function Todos({ projectId }: { projectId: string }) { const todos = useLive(() => { return db.todo.where({ projectId }).orderBy("createdAt", "desc").all; }); return todos.map((todo) => { return ; }); } const TodoRow = live(({ todo }: { todo: Todo }) => { return ( { todo.update({ title: event.target.value }); }} /> ); }); ``` No `fetch`, no API route, no cache keys. The rename is checked against your permissions on the server, and every teammate looking at the list sees it. ## It works with what you have - **Postgres**, any provider (Neon, Supabase, RDS, local). Your data stays in your tables. - **Prisma**: your `schema.prisma` stays the source of truth. clientdb reads your models from it. - **Next.js**: one route handler serves everything. It runs on serverless hosts like Vercel with no background process. - **React** (with or without MobX), and a native **Swift** client for iPhone and Mac. There's no hosted service and nothing to sign up for. clientdb is a library that runs in your app. ## When it's a good fit clientdb shines in apps where people work with their own or their team's data and expect it to feel fast: project tools, CRMs, dashboards, editors, internal tools. The approach is inspired by apps like Linear, which feel instant because the data is already on your device. It's less of a fit for public, content-heavy sites (a blog, a store catalogue) where every visitor sees the same pages and there's nothing personal to keep locally. ## Where to go next The whole model in two minutes. Add clientdb to your existing Next.js + Prisma app. Every part of the API in one example app. Who may see and change what. Queries, relations and live updates in React. The docs are available as plain text for LLMs: [/llms.txt](/llms.txt) (an index) and [/llms-full.txt](/llms-full.txt) (every page). Each page also has a "Copy page as Markdown" button. The packages are on npm: `npm install @clientdb/client @clientdb/server`, and the rest are listed in [Installation](/docs/installation). The client packages are Apache-2.0; the server engine is FSL-1.1-ALv2, which allows running it as the backend of your own app. --- # How it works, in 5 pictures > The whole idea in two minutes. No sync theory needed. ## 1. Each user gets a copy of their data Your data stays in your Postgres, as it is today. When someone opens your app, clientdb downloads the rows **they are allowed to see** into their browser (or iPhone) and keeps them there, saved to disk so the next visit starts instantly, even offline. You choose what comes up front: small models, such as a user's projects and todos, arrive when the app opens. Bigger ones, such as comments, arrive the first time something reads them, and stay. Alice and Bob get different copies: each one only ever receives what your permissions say they may read. ## 2. Reading is instant, because the data is already there Your components read from that local copy, like reading a variable: ```tsx import { useLive } from "@clientdb/react"; import { db } from "@/sync/db"; const todos = useLive(() => { return db.todo.where({ projectId }).orderBy("createdAt", "desc").all; }); ``` No request, no loading state, no cache to manage. Filtering and sorting happen in memory and stay fast with 100,000 rows. When the data changes, the component re-renders on its own. For data that isn't on the device yet, the same read starts loading it, and the component shows what's there until the rest arrives. ## 3. Writing is instant too, and your server still decides ```ts todo.update({ title: "Fix the login redirect" }); ``` The change shows on screen immediately and is sent to your server in the background. The server checks it against your permissions file. If it's allowed, it's saved to Postgres. If not, the change is undone on the user's screen and you get an error you can show. Nobody can write around your rules from the browser. This is why you don't need API routes per feature: one route serves everything, and one permissions file says who may read and write what. ## 4. Changes reach everyone who can see them Once a change is saved, clientdb sends it to every other device that is allowed to see it. Open tabs pick it up on their next sync (on load, on focus and after each write), or within milliseconds with live updates turned on. A device that was offline catches up when it reconnects, getting only what changed while it was away. Changes your own server code makes with Prisma or SQL sync the same way: small database triggers notice them, so that code doesn't change. ## 5. When permissions change, data appears and disappears correctly Permissions aren't fixed. People get promoted, removed from projects, todos get marked private. When that happens, clientdb works out who just gained access and who just lost it, sends the newly visible rows to the first group and tells the second to remove theirs. You write no code for this; it follows from the same permissions file. ## That's the whole model - **Your Postgres** is the source of truth, unchanged. - **One permissions file** decides what each user can read and write. - **Each device** holds a copy of its user's data, reads it instantly and writes to it instantly. - **clientdb** keeps every copy in sync and correct. Ready to try it on your app? Go to the [quick start](/docs/quick-start). Want the ideas that shape your code? Read [Thinking in clientdb](/docs/thinking-in-clientdb). Curious how it works inside? See [Under the hood](/docs/concepts). --- # Quick start: Next.js + Prisma > Add clientdb to the Next.js + Prisma app you already have. Everything runs inside your app; nothing else to host. By the end of this page, your existing app's data will be available in the browser, instantly readable and writable, and kept in sync with Postgres. Nothing new to host: it all runs in a Next.js route handler, so it works on Vercel and Neon as is. The examples come from a small todo app: users, projects, project members (with the role `member` or `admin`) and todos. Swap in your own models as you go. Here's what you'll add, and why: | Step | What | Why | |---|---|---| | 1 | A Prisma generator and a few bookkeeping tables | clientdb reads your models from `schema.prisma` and needs a place to track what it has synced | | 2 | `schema.ts` | picks which models and columns go to browsers, and which load up front | | 3 | a `permissions/` folder, one file per model | says who may read and write what (this replaces your API checks) | | 4 | the engine and a route handler | the one endpoint browsers talk to | | 5 | a triggers migration | so changes your server makes with Prisma (or SQL) reach browsers too, without changing that code | | 6 | a deploy step | lets clientdb pick up rows that existed before it | | 7 | the client | reads and writes from React | New to the idea? Read [How it works, in 5 pictures](/docs/how-it-works) first; it takes two minutes. Install the packages first; see [Installation](/docs/installation). ## 1. Add the generator and clientdb's tables Add the generator to `prisma/schema.prisma`: ```prisma title="prisma/schema.prisma" generator clientdb { provider = "clientdb-prisma" output = "../src/generated/clientdb" } ``` Append the engine's own tables as Prisma models. Prisma then owns every table, and clientdb never runs DDL: ```bash npx clientdb-prisma models >> prisma/schema.prisma # or a separate file in a multi-file schema npx prisma migrate dev --name clientdb npx prisma generate # writes src/generated/clientdb/index.ts ``` The generator fails with a clear message when the engine models are missing. ## 2. The schema, shared by server and browser ```ts title="src/sync/schema.ts" import { fromPrisma } from "@clientdb/prisma"; import { prismaModels } from "../generated/clientdb"; export const schema = fromPrisma(prismaModels, { omit: { User: ["passwordHash"] }, // stays on the server models: { User: { load: "eager" }, Project: { load: "eager" }, Member: { load: "eager" }, Todo: { load: "eager" }, }, }); export type Schema = typeof schema; ``` - **`load: "eager"`**: every row of the model this user may read arrives when the app starts, so reading it never waits. Use it for models that stay small per user. - **Lazy, the default**: the rest load when something reads them. Comments arrive per todo, the first time `todo.comments` is read. - **Relations and `onDelete` come from `schema.prisma`**: `Comment.todo` says `onDelete: Cascade` there, so deleting a todo deletes its comments on every device too, and undo brings them back. Everything is typed against your Prisma models: a misspelled field or relation is a compile error. `schema` also remembers which table and columns each model uses, so it's the only thing the rest of your code passes around. Auth models such as `Session` and `Account` never sync. A column whose name looks secret (token, secret, hash, password, salt, key) must be listed in `omit` (stays on the server) or `notSecret` (fine to send) before the schema builds, so a new `apiToken` column never reaches browsers by accident. See [Prisma](/docs/schema/prisma) for the mapping. ## 3. Permissions, server only Permissions live in one file per model. Each rule receives the row and `$`, the permission helpers: `$.viewer.id` is the signed-in user, and `$.anyOf`, `$.and` and the others combine conditions. Everything is typed against your schema. Start with the project. Conditions you use in several models, such as "the viewer is a member of this project", are defined once with `defineRule` and imported where they're needed: ```ts title="src/sync/permissions/project.ts" import { defineModelRules, defineRule } from "@clientdb/server"; import { schema } from "../schema"; export const isMember = defineRule(schema, "project", (project, $) => { return project.members.some((member) => { return member.userId.is($.viewer.id); }); }); export const isAdmin = defineRule( schema, "project", (project, $) => { return project.members.some((member) => { return $.and(member.userId.is($.viewer.id), member.role.is("admin")); }); }, { name: "project.admin" }, // optional: a stable, readable id for a widely shared condition ); export const projectRules = defineModelRules(schema, "project", { read: (project) => { return isMember(project); }, update: { when: (project) => { return isAdmin(project); }, fields: ["name"], }, }); ``` Then the todos: ```ts title="src/sync/permissions/todo.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; import { isAdmin, isMember } from "./project"; export const todoRules = defineModelRules(schema, "todo", { read: (todo, $) => { return $.anyOf({ shared: [todo.isPrivate.is(false), isMember(todo.project)], author: todo.authorId.is($.viewer.id), admin: isAdmin(todo.project), }); }, create: { when: (todo) => { return isMember(todo.project); }, enforce: ($) => ({ authorId: $.viewer.id }), }, update: { when: (todo) => { return isMember(todo.project); }, fields: ["title", "done"], }, delete: { when: (todo, $) => { return $.anyOf({ author: todo.authorId.is($.viewer.id), admin: isAdmin(todo.project), }); }, }, }); ``` `$.anyOf` passes when any one of its branches does. Each key is a short label for a branch, and an array means every condition in it must hold. The labels show up in errors, for example `Forbidden: todo.delete (author: no, admin: no)`. `enforce` lists fields that must equal a value. Here every todo this user creates must have their own id as `authorId`, so nobody can create a todo in someone else's name. The browser sends `authorId: db.$session.viewerId` itself; a write with any other value is rejected with `Forbidden: todo.authorId must equal the viewer's id`. Rules only check, they never change data. ```ts title="src/sync/permissions/member.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; import { isAdmin, isMember } from "./project"; export const memberRules = defineModelRules(schema, "member", { read: (member) => { return isMember(member.project); }, update: { when: (member) => { return isAdmin(member.project); }, fields: ["role"], // promotion and demotion sync automatically }, delete: { when: (member, $) => { return $.anyOf({ admin: isAdmin(member.project), leaving: member.userId.is($.viewer.id), }); }, }, }); ``` Comments are readable whenever their todo is, so their read rule says exactly that: ```ts title="src/sync/permissions/comment.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; export const commentRules = defineModelRules(schema, "comment", { read: (comment, $) => { return $.canRead(comment.todo); }, create: { when: (comment, $) => { return $.canRead(comment.todo); }, enforce: ($) => ({ authorId: $.viewer.id }), }, }); ``` `$.canRead(comment.todo)` holds when the viewer may read the comment's todo under the todo rule above. When a todo becomes private, its comments leave the devices that lose it, re-tagged in bulk. ```ts title="src/sync/permissions/user.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; import { isMember } from "./project"; export const userRules = defineModelRules(schema, "user", { read: (user, $) => { return $.anyOf({ self: user.id.is($.viewer.id), teammate: user.memberships.some((membership) => { return isMember(membership.project); }), }); }, }); ``` Finally, combine the files with `definePermissions`: ```ts title="src/sync/permissions/index.ts" import { definePermissions } from "@clientdb/server"; import { schema } from "../schema"; import { commentRules } from "./comment"; import { memberRules } from "./member"; import { projectRules } from "./project"; import { todoRules } from "./todo"; import { userRules } from "./user"; export const permissions = definePermissions(schema, [userRules, projectRules, memberRules, todoRules, commentRules]); ``` In development a model without a read rule is an error that names it; list models that should never reach devices in `fromPrisma`'s `serverOnly` (or `exclude`). A missing write rule refuses that operation, and defining the same model in two files is an error. See [Permissions](/docs/server/permissions). ## 4. The engine and the route handler ```ts title="src/sync/engine.ts" import { createEngine } from "@clientdb/server"; import { permissions } from "./permissions"; export const engine = createEngine({ permissions }); ``` ```ts title="src/app/api/sync/[...path]/route.ts" import { clientdbHandler } from "@clientdb/server/next"; import { auth } from "@/lib/auth"; // e.g. Better Auth import { engine } from "@/sync/engine"; export const { GET, POST } = clientdbHandler(engine, { session: async (request) => { const session = await auth.api.getSession({ headers: request.headers }); if (!session) { return null; // signed out: the request is refused with 401 } return { viewer: session.user.id }; // the id of the signed-in user's `User` row }, }); ``` `session(request)` is the only place clientdb learns who is signed in: the browser never says who it is, your server does. It's called on every request, so signing out takes effect at once. It can also return `readOnly: true` for a user who may read but not write, and claims such as "staff" (see [Permission recipes](/docs/guides/permission-recipes#staff-and-other-facts-about-the-session)). Same-origin requests carry the session cookie. The handler serves every endpoint the client uses: `…/bootstrap` (the first load), `…/pull` and `…/push` (sync), `…/partial` (lazy loads) and `…/query` (server queries). No route segment config is needed: route handlers run on Node.js by default (Postgres needs TCP), and a handler that reads the request is always dynamic. Don't add `export const runtime` or `export const dynamic`: Next 16 rejects both when `cacheComponents` is on, which `create-next-app` enables by default. ## 5. Install the change triggers Your app keeps writing with Prisma in tRPC routers, server actions and webhooks. For browsers to see those changes, clientdb ships Postgres triggers that note which rows changed. They come as a regular Prisma migration: ```bash npx clientdb-prisma triggers src/sync/schema.ts > prisma/migrations/20261202_clientdb_triggers/migration.sql npx prisma migrate dev ``` `triggers` reads your schema module and covers every model it syncs. After that, your write code needs no clientdb calls at all: ```ts title="src/app/projects/actions.ts" "use server"; import { prisma } from "@/lib/prisma"; export async function addTodo(projectId: string, authorId: string, title: string) { await prisma.todo.create({ data: { projectId, authorId, title } }); // nothing else to add } ``` The triggers catch nested writes, `createMany` / `updateMany` / `deleteMany`, raw SQL, other services and rows removed by `ON DELETE CASCADE`. They are part of the same transaction as the write, so nothing is lost if it rolls back. The engine picks the changes up on the next pull or push. Run the command again, into a new migration, when you add or remove a synced model. Other browsers see the change on their next sync: on focus, every 30 seconds while the tab is visible, or at once with live updates. The tab that called the action can wait for it with `db.$action`, which runs the function and then syncs: ```tsx title="src/app/projects/AddTodo.tsx" "use client"; import { addTodo } from "./actions"; import { db } from "@/sync/db"; export function AddTodo({ projectId, userId }: { projectId: string; userId: string }) { return ( ); } ``` As a safety net, `await engine.reconcile()` compares your tables with what clientdb last synced and sends any differences. `engine.migrate()` runs it too (next step), and you can also run it from a cron job. See [Writes from your server](/docs/guides/untracked-rows). ## 6. Adopt existing rows, once per deploy ```bash # after `prisma migrate deploy`, e.g. in your release step npx clientdb migrate src/sync/engine.ts ``` It runs `engine.migrate()` on your engine, prints what it did and exits. Until it has run for the current schema and rules, the route handler refuses to serve (`503 NotMigrated`) and logs why. Migrations take a session-level advisory lock, so they need a direct (non-pooled) connection: set `DIRECT_URL` when `DATABASE_URL` goes through a pooler (a pooler URL is refused). The first run adopts every row that existed before clientdb. Every later run also reconciles your tables with clientdb's copies, so anything written before the triggers were installed is picked up. See [Untracked rows](/docs/guides/untracked-rows). ## 7. The client ```ts title="src/sync/db.ts" "use client"; import { createDatabaseClient, indexedDb, type EntitiesOf } from "@clientdb/client"; import { schema, type Schema } from "./schema"; export const db = createDatabaseClient({ schema, storage: indexedDb(), // keeps data and unsent changes on the device; tabs share one connection }); /** Every model's entity type, by name: `DB["Todo"]`, `DB["Project"]`. */ export type DB = EntitiesOf; export type Todo = DB["Todo"]; export type Project = DB["Project"]; ``` That's all the configuration. The client syncs with `/api/sync` over plain HTTP: on load, when the window regains focus, after writes and on an interval. Creating it at module level is safe: it does nothing until it's first used in the browser. The local data is kept per signed-in user automatically. Wrap your app in `DatabaseProvider`. With `ready`, it shows the fallback until the eager models are loaded, from IndexedDB or the network: ```tsx title="src/app/providers.tsx" "use client"; import { DatabaseProvider } from "@clientdb/react"; import { Spinner } from "@/components/spinner"; import { db } from "@/sync/db"; export function Providers({ children }: { children: React.ReactNode }) { return ( }> {children} ); } ``` Then read models straight from `db` in any component: ```tsx title="src/app/projects/[projectId]/todos.tsx" "use client"; import { live, useLive } from "@clientdb/react"; import { db, type Todo } from "@/sync/db"; // live() tracks every field and relation read while rendering: the checkbox and author stay current. const TodoRow = live(({ todo }: { todo: Todo }) => { return (
  • { todo.update({ done: !todo.done }); }} /> {todo.title} · {todo.author.name}
  • ); }); export function Todos({ projectId }: { projectId: string }) { const todos = useLive(() => { return db.todo.where({ projectId }).orderBy("createdAt", "desc").limit(50).all; }); return (
      {todos.map((todo) => { return ; })}
    ); } ``` `useLive` tracks only what its function reads: here, which todos are in the list. Reading `todo.done` or `todo.author.name` in `Todos` itself would not be tracked, and the row would keep showing its first value. Read per-row data inside a `live()` component, or inside `useLive`. In development, such untracked reads during render log a warning. See [Reactivity](/docs/client/reactivity). ```ts // writes: on screen at once, then confirmed by the server await todo.update({ title: "Ship it" }).confirmed; ``` Comments aren't eager, so the first read of `todo.comments` loads that todo's comments. Until they arrive, `todo.comments.status` is `"loading"`; see [Reading data](/docs/client/queries#lazy-models-load-when-read). On sign-out, call `await db.$clear()` to delete the local data and unsent changes, so the next person on a shared computer doesn't see them. ## What you have now - When someone opens your app, their browser downloads the data they may see and saves it. The next visit starts from that copy, even offline, and fetches only what changed. - Reads come from that copy, so your components render immediately. - Writes show up at once and are checked against your permissions on your server before they're saved. - Changes your server makes with Prisma or SQL reach browsers too, with no extra code, thanks to the triggers. - When someone's access changes (promoted, removed from a project), the right data appears on or disappears from their devices. ## Check it works: the two-browser test 1. Sign in as one user in your normal browser and as a teammate in a private window. 2. Open the same project in both. 3. Rename a todo in one window. It changes there immediately, and in the other window on its next sync (switch to it: syncing on focus is on by default), or within milliseconds with [live updates](/docs/transports/websocket). 4. Remove the teammate from the project in your database (Prisma Studio, psql or your admin UI). Their window loses the project's data on its next sync. Next: write the rules for the rest of your models with the [permission recipes](/docs/guides/permission-recipes), or learn [how React components stay up to date](/docs/client/reactivity). --- # Thinking in clientdb > The mental model in seven ideas: a local replica your UI reads and writes instantly, and a server that has the final say. In most web apps, data lives on the server and the UI borrows it: a component asks for data, waits, shows a spinner, caches the answer and hopes it stays fresh. clientdb changes one thing, and the rest of this page follows from it: **the data your UI needs is already on the device.** Hold on to that idea and every other page in these docs will feel obvious. The examples use the same small todo app as the [quick start](/docs/quick-start): users, projects, project members and todos with comments. ## 1. The local replica is the UI's source of truth; the server is the authority Each device keeps a **local replica**: a copy of the rows its user is allowed to read, held in memory and saved to disk. Your components only ever talk to that replica. They never wait for the network: what isn't there yet [loads in the background](#5-which-data-lives-on-the-device), and the replica fills in. The replica syncs with your server in the background. Your server, and the Postgres behind it, keep the final word: they decide which rows reach the device and whether a change is allowed. So there are two roles, and they never mix: - **the replica** answers "what should the screen show right now?"; - **the server** answers "what is true, and who may change it?". ## 2. Reads are synchronous queries over local data Because the rows are already on the device, reading them is a plain function call. It returns data, not a promise: ```tsx title="src/app/projects/OpenCount.tsx" import { useLive } from "@clientdb/react"; import { db } from "@/sync/db"; export function OpenCount({ projectId }: { projectId: string }) { const openCount = useLive(() => { return db.todo.where({ projectId, done: false }).count; }); return {openCount} open; } ``` The same goes for single rows and the signed-in user: ```ts import { db } from "@/sync/db"; const todo = db.todo.get(todoId); // the todo, or undefined: never a promise const greeting = `Hi, ${db.$viewer?.name}`; // the signed-in user's own row ``` There is **no loading state for data already on the device**: no `isPending`, no spinner per component. `useLive` (or a `live()` component) re-runs the query whenever the rows it read change, whoever changed them. See [Reading data](/docs/client/queries) and [Reactivity](/docs/client/reactivity). ## 3. Writes apply instantly, then confirm or roll back A write changes the replica first, so every query that reads it updates on this frame. The change is then sent to the server in the background: ```ts import { db } from "@/sync/db"; const todo = db.todo.create({ projectId, authorId: db.$session.viewerId!, title: "Write release notes" }); todo.id; // already there: ids are generated on the device const handle = todo.update({ done: true }); // on screen now await handle.confirmed; // the server accepted it ``` This is an **optimistic write**. If the server accepts it, nothing visible happens: the screen already shows the result. If the server refuses it (a permission rule says no, say), the change is rolled back on screen, `confirmed` rejects with the reason, and you can show it with a toast. Meanwhile, changes from other people keep arriving underneath your pending ones, and when two people edit the same field, the last write the server commits wins on every device. See [Writing data](/docs/client/mutations), [Transactions and undo](/docs/client/transactions) and, for the details, [Conflicts and rejections](/docs/server/conflicts). ## 4. One shared schema, and the server enforces the rules The schema is one file that both the server and the browser import. It types every query, write and rule: ```ts title="src/sync/schema.ts" import { createSchema, model, t } from "@clientdb/schema"; const user = model({ name: t.string(), email: t.string().unique() }, { load: "eager" }); const project = model({ name: t.string() }, { load: "eager" }); const member = model( { // adds the `userId` column, `member.user` and `user.memberships` user: t.belongsTo("user", { inverse: "memberships" }), project: t.belongsTo("project", { inverse: "members" }), role: t.enum(["member", "admin"]).default("member"), }, { load: "eager" }, ); const todo = model( { project: t.belongsTo("project", { inverse: "todos" }), author: t.belongsTo("user", { inverse: "todos" }), title: t.string(), done: t.boolean().default(false), isPrivate: t.boolean().default(false), createdAt: t.timestamp().defaultNow(), updatedAt: t.timestamp().updatedAt(), // set on create and on every update, on the device at once }, { load: "eager" }, ); const comment = model({ todo: t.belongsTo("todo", { inverse: "comments", onDelete: "cascade" }), // deleted with its todo author: t.belongsTo("user", { inverse: "comments" }), body: t.string(), createdAt: t.timestamp().defaultNow(), }); // Every model gets an `id`, and is named by its key here export const schema = createSchema({ user, project, member, todo, comment }); export type Schema = typeof schema; ``` With Prisma, [`fromPrisma`](/docs/schema/prisma) builds the same schema from your `schema.prisma`. The browser can run any code it likes, so it is never trusted. The rules live on the server, next to the schema, and they come in two kinds: ```ts title="src/sync/permissions/todo.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; import { isAdmin, isMember } from "./project"; export const todoRules = defineModelRules(schema, "todo", { read: (todo, $) => { return $.anyOf({ shared: [todo.isPrivate.is(false), isMember(todo.project)], author: todo.authorId.is($.viewer.id), admin: isAdmin(todo.project), }); }, create: { when: (todo) => { return isMember(todo.project); }, enforce: ($) => ({ authorId: $.viewer.id }), }, }); ``` - **Read rules decide which rows ever reach a device.** The server filters before it sends, so a private todo never leaves the server for someone who may not see it. There is nothing to hide in the UI, because it isn't there. - **Write rules check every change.** `when` says who may make it. `enforce` lists fields that must equal a value: here, a new todo's `authorId` must be the signed-in user. Rules only check, they never change data, which is why the client passes `authorId: db.$session.viewerId` itself and shows the right author at once. - **Some data never leaves the server.** Mark a model `serverOnly: true` (with Prisma, list it in the `serverOnly` option of `fromPrisma`): rules can still read it, but devices never receive it and the client has no API for it. For single columns, such as a password hash, the `omit` option of `fromPrisma` does the same. A column only some users may see, such as a license key, is [restricted](/docs/guides/permission-recipes#fields-only-some-users-may-see): it has a read rule of its own. See [Schema](/docs/schema) and [Permissions](/docs/server/permissions). ## 5. Which data lives on the device "The data is on the device" means the rows **this user may read**, and you choose when each model arrives with its `load` option: | `load` | When the rows arrive | In the todo app | |---|---|---| | `"eager"` | when the app starts; `DatabaseProvider` shows its fallback until they are there | users, projects, members, todos | | `"lazy"` (default) | the first time something reads them, then they stay | comments | Eager models are what make reads instant everywhere, so mark the models a user works with all the time, as long as they stay small per user. Everything else is lazy: too large, or too rarely used, to download up front. A lazy read loads exactly what it asked for: `todo.comments` loads that todo's comments, `db.user.where({ email })` the user with that email (the field is `.unique()`), `db.comment.get(id)` one comment, and `db.comment.all` every comment the user may read. That first read is the one place a loading state shows up: ```tsx title="src/app/Comments.tsx" import { live } from "@clientdb/react"; import { Spinner } from "@/components/spinner"; import type { Todo } from "@/sync/db"; export const Comments = live(({ todo }: { todo: Todo }) => { const comments = todo.comments.all; // the first read loads this todo's comments if (todo.comments.isLoading) { return ; } return comments.map((comment) => { return

    {comment.body}

    ; }); }); ``` Once a todo's comments have arrived, they stay on the device and stay current like everything else. To find rows that aren't on the device, such as searching every comment for a word, ask the server with `db.comment.query(…)`. See [Reading data](/docs/client/queries#lazy-models-load-when-read). ## 6. Undo, history and offline come with the replica Every write is a small transaction recorded on the device, so the client keeps a history of them, and undo is one call: ```ts import { db } from "@/sync/db"; db.$undo(); // sends the inverse change, checked by the server like any other write db.$redo(); db.$canUndo; // reactive, for an enabled/disabled button ``` Undo leaves alone any field someone else changed since, so it never overwrites a teammate's work. See [Undo and redo](/docs/client/transactions#undo-and-redo). Offline works for the same reason. Reads come from the replica, which doesn't need the network. Writes apply locally, wait on disk and are sent when the connection is back, each applied at most once. With [storage](/docs/storage), the next visit opens from disk, before any request, and fetches only what changed while the app was closed. ## 7. What you stop writing Most of the data code in a typical app exists to move data between the server and the screen, and to cope with the wait. With a replica on the device, that code has nothing left to do: | You used to write | With clientdb | |---|---| | an API route and a `fetch` per read and per write | one route handler, and the rules file | | a client cache, with query keys | the replica is the cache | | a loading spinner per component | reads return data; one fallback while the app first loads | | invalidation and refetching after each write | every query that read a row updates when it changes | | optimistic updates, and rolling them back by hand | every write is optimistic and rolls back on its own | | permission checks repeated in each route | read and write rules, declared once per model | What's left is the part that is about your app: the schema, the rules, and components that read and write data as if it were local, because it is. Logic that must run on the server (charging a card, sending an email) stays in your own server actions, tRPC routes or API handlers, writing with Prisma as today. Wrap the call in `db.$action`, and it resolves once the rows that call wrote are on the device: ```ts import { db } from "@/sync/db"; import { inviteTeammate } from "./actions"; // a server action that writes with Prisma and sends an email await db.$action(() => { return inviteTeammate(projectId, "sam@example.com"); }); ``` See [Writing data](/docs/client/mutations#server-logic-with-action). ## Where to go next Add clientdb to your Next.js + Prisma app. Read and write rules in full. Queries, relations and lazy models. Atomic writes, undo and rejections. --- # 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](#with-prisma-fromprisma). 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. ```ts title="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"]] }, ); ``` ```ts title="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 }, ); ``` ```ts title="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 {} 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 option | Meaning | |---|---| | `t.string()`, `t.number()`, `t.boolean()`, `t.enum([…])`, `t.json()` | 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 field | every 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](/docs/schema) 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: ```ts title="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`. - `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](/docs/schema/prisma) for the mapping. ## Load modes | `load` | Rows 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 title="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]) } ``` ```bash 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 ` 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: ```ts title="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](/docs/guides/untracked-rows). ## 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: ```ts title="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`. ```ts title="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. ```ts title="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. ```ts title="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](/docs/server/permissions). ## The signed-in session Your server says who is signed in; the browser never does: ```ts title="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 { 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](#nextjs)). 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)`. ```ts title="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 ```ts title="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: ```ts title="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 }; ``` ```ts title="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 }); ``` ```ts title="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: ```ts title="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](/docs/transports/http), [Node.js servers](/docs/transports/node) and [Live updates](/docs/transports/websocket). ## Clients ```ts title="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" }, }); ``` ```ts title="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. ```ts title="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; /** The admin panel's entities: fields and relations, no writes. */ export type AdminPayment = ReadOnlyEntity; ``` 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. ```tsx title="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 (
  • {device.name} · {device.license.subscription.plan} · seen {lastSeen}
  • ); }); export function DevicesPage() { const devices = useLive(() => { return dashboardDb.$viewer?.devices.orderBy("lastSeenAt", "desc").all ?? []; }); return (
      {devices.map((device) => { return ; })}
    ); } ``` ```tsx title="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 (

    #{payment.invoiceNumber} · {payment.amount} {payment.currency} · {payment.status}

    ); }); }); ``` See [Reading data](/docs/client/queries) and [React](/docs/client/reactivity). ## 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: ```tsx title="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 (
    {results.status !== "complete" && } {results.all.map((customer) => { return ( { adminDb.user.where({ email: customer.email }).preload(); }} > {customer.email} · {customer.subscriptions.count} subscriptions ); })} {results.hasMore && ( )}
    ); }); ``` | `results.status` | Meaning | |---|---| | `"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: ```tsx title="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" ?

    No customer with this email

    : ; } return (

    {customer.name}

    {customer.subscriptions.all.map((subscription) => { return (

    {subscription.plan} · {subscription.status} · {subscription.licenses.count} seats

    {subscription.payments.all.map((payment) => { return ; })}
    ); })}
    ); }); ``` ## 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. ```ts title="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](/docs/client/mutations) and [Transactions and undo](/docs/client/transactions). ## 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. ```ts title="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: ```ts title="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: ```ts title="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 ```tsx title="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 ( ); } if (status === "offline") { return Offline; } return {pendingCount > 0 ? "Saving…" : "Saved"}; } export function Providers({ children }: { children: ReactNode }) { return ( }> {children} ); } ``` `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. ```ts title="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: ```ts title="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](#nextjs)) 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](/docs/server/archive-delete)). Pruning runs on every `clientdb migrate`, hourly in a process that called `engine.start()`, and whenever you call `engine.prune()`. ```bash # 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](/docs/server/migrations). --- # Installation > Install the clientdb packages from npm. ## Requirements - Node 22 or newer - Postgres 14 or newer (CI runs 16 and 17) - TypeScript 5.5 or newer (the repo itself uses TypeScript 7) - Prisma 7, if you use the Prisma integration ## Add the packages For a Next.js app with Prisma and React: ```bash npm install @clientdb/schema @clientdb/client @clientdb/server @clientdb/prisma @clientdb/react ``` | Package | What it's for | |---|---| | `@clientdb/schema` | models, fields, relations and claims, shared by server and clients | | `@clientdb/client` | the database on the device; test helpers in `@clientdb/client/testing` | | `@clientdb/server` | permission rules, the sync engine, the route handler (`@clientdb/server/next`), test helpers (`@clientdb/server/testing`) and the `clientdb` command | | `@clientdb/prisma` | builds the schema from your Prisma models; the generator, the bookkeeping models and the triggers (`clientdb-prisma`) | | `@clientdb/react` | `live()`, `useLive()` and `DatabaseProvider` | | `@clientdb/mobx` | instead of, or next to, `@clientdb/react`: makes the data MobX-observable (`mobx` is a peer dependency) | Without Prisma, leave out `@clientdb/prisma` and write the [schema in TypeScript](/docs/schema). The packages ship compiled JavaScript with types, so there's nothing to add to `next.config.ts`. The server package uses `pg` over TCP. Next.js route handlers run on Node.js by default, so no route segment config is needed; don't add `runtime` or `dynamic` exports (Next 16 rejects them with `cacheComponents`). ## Licenses The packages that run in your app's clients (`schema`, `client`, `core`, `react`, `mobx`) are Apache-2.0. The server engine (`server`, `prisma`) is FSL-1.1-ALv2, which becomes Apache-2.0 two years after each release. Running the engine as the backend of your own app, commercial or not, is allowed. See [LICENSE.md](https://github.com/pie6k/clientdb/blob/main/LICENSE.md). ## Working on clientdb itself ```bash corepack enable # once; uses the Yarn version pinned in package.json yarn install yarn workspace @clientdb/prisma generate # Prisma fixture client (needed by typecheck and Prisma tests) yarn typecheck yarn test # server and Prisma tests need CLIENTDB_TEST_PG=postgres://… yarn spec:generate # regenerate spec vectors (CI checks they are current) yarn web dev # this website ``` --- # Reading data > Synchronous, typed, reactive reads: lookups, filters, relations, lazy loads, server queries and eviction. Every read is synchronous: it returns what's on the device right away, never a promise. Collections are reactive and, while observed, maintained incrementally from each change. The examples use the todo app from the [quick start](/docs/quick-start): users, projects, members, todos (eager) and comments (lazy). ## Getting the database The client is the database: models hang directly off it (`db.todo`), and the client's own members start with `$` (`db.$ready()`, `db.$undo()`), so they never collide with a model name. ```ts title="src/sync/db.ts" "use client"; import { createDatabaseClient, indexedDb, type EntitiesOf } from "@clientdb/client"; import { schema, type Schema } from "./schema"; export const db = createDatabaseClient({ schema, storage: indexedDb() }); export type DB = EntitiesOf; export type Todo = DB["Todo"]; ``` ## Lookups and whole models ```ts import { db } from "@/sync/db"; db.todo.get(todoId); // Todo | undefined, archived rows included db.todo.all; // readonly Todo[] db.todo.count; db.todo.first; // Todo | null db.todo.isEmpty; ``` ## Filtering, ordering, limits ```ts import { db } from "@/sync/db"; const recent = db.todo .where({ projectId, done: false, createdAt: { gte: Date.now() - 7 * 24 * 3600_000 } }) .orderBy("createdAt", "desc") .orderBy("title") // later orderBy calls are tie-breakers .limit(20) .all; // live, maintained incrementally while observed const releaseTodos = db.todo.where({ title: { contains: "release", mode: "insensitive" } }).all; ``` - A value means equality; an array means "any of". - `gt`, `gte`, `lt` and `lte` compare numbers, timestamps and text. Timestamps are numbers: milliseconds since 1970. - `contains`, `startsWith` and `endsWith` match text; `mode: "insensitive"` ignores case. - `orderBy` takes a field name or a function, and a direction (`"asc"` by default). Without `orderBy`, the order is unspecified. - A predicate is allowed too, but it re-runs on every change instead of being maintained incrementally: ```ts import { db } from "@/sync/db"; const shortTitles = db.todo.where((todo) => { return todo.title.length < 10; }); ``` Queries are interned by their filters while observed and released when nothing observes them, so writing the same query in two components costs one. ## Collections Every collection (`db.todo`, a `where(…)`, a relation like `project.todos`) has the same shape: | Member | Meaning | |---|---| | `all`, `first`, `last`, `count`, `isEmpty` | the current result | | `get(id)` | a member by id, or `undefined` | | `where`, `orderBy`, `limit` | a refined collection | | `includeArchived()` | include archived rows (hidden by default) | | `status` | `"complete"`, `"loading"` or `"partial"` (see [lazy models](#lazy-models-load-when-read)) | | `isLoading` | `true` while missing rows are being fetched | | `preload()` | start fetching missing rows early, as an optimisation; returns a promise | ## Relations Relations are typed from the schema and indexed on the foreign key: ```ts import type { Todo } from "@/sync/db"; export function describe(todo: Todo) { const projectName = todo.project.name; // to-one const authorName = todo.author.name; // to-one, through `authorId` const openInProject = todo.project.todos.where({ done: false }).count; // the inverse collection return `${projectName} · ${authorName} · ${openInProject} open`; } ``` ## Lazy models load when read A model is lazy unless it says `load: "eager"`. Its rows arrive the first time a read needs them, and stay. You don't fetch them yourself: reading a collection (`.all`, `.count`, `.first` and so on) or a row loads whatever it's missing, by what the read names: | Read | Loads | |---|---| | `todo.comments` | the comments of this todo (a foreign key) | | `db.user.where({ email })` | the user with that email (a `.unique()` field) | | `db.comment.get(id)` | that comment | | `db.comment.all`, or a `where` on other fields | every comment the user may read | Reads in the same tick are batched into one request, and each set of rows is fetched only once. While rows are on their way, the collection returns what it has (often nothing), `isLoading` is `true` and `status` is `"loading"`. When they arrive, everything that read the collection updates: ```tsx title="src/app/Comments.tsx" import { live } from "@clientdb/react"; import { Spinner } from "@/components/spinner"; import type { Todo } from "@/sync/db"; export const Comments = live(({ todo }: { todo: Todo }) => { const comments = todo.comments.orderBy("createdAt").all; // the first read loads this todo's comments if (todo.comments.isLoading) { return ; } return comments.map((comment) => { return

    {comment.body}

    ; }); }); ``` Every way in is separate. If comments belong to a todo (`todoId`) and an author (`authorId`), `todo.comments` and `user.comments` each load on their own: reading one user's comments loads all of them, even when some are already on the device because their todos were opened. Until then `user.comments.status` is `"partial"`: some rows are here, not all. The server loads these rows with `WHERE "todoId" = $1` (or `"authorId"`). Tables clientdb creates index every foreign key; on your own tables (Prisma), add an index for each foreign key of a lazy model, such as `@@index([authorId])`. ### `preload()`: fetching early `preload()` starts the same fetch before anything reads the collection. It is only an optimisation, for example to fetch a todo's comments when the pointer hovers over its link, so they're there by the time it opens. It returns a promise that resolves when the rows have arrived. ```tsx title="src/app/TodoLink.tsx" import { live } from "@clientdb/react"; import type { Todo } from "@/sync/db"; export const TodoLink = live(({ todo }: { todo: Todo }) => { return ( { todo.comments.preload(); }} > {todo.title} ); }); ``` ### Eager relations come along `eager: true` on a relation makes children travel with their parent: whenever a parent row arrives, however it arrived, its children come in the same response. With `eager: true` on `comment.todo`, a todo that loads brings its comments, so `todo.comments` is complete at once. ```ts title="src/sync/schema.ts" import { fromPrisma } from "@clientdb/prisma"; import { prismaModels } from "../generated/clientdb"; export const schema = fromPrisma(prismaModels, { omit: { User: ["passwordHash"] }, models: { User: { load: "eager" }, Project: { load: "eager" }, Member: { load: "eager" }, Todo: { load: "eager" }, Comment: { relations: { todo: { eager: true } } }, }, }); export type Schema = typeof schema; ``` The cascade only goes down, from parents to the children marked `eager`, and on from those. The rows those children point at (a comment's author) come along as single rows. It stops at a model it already passed through, and at 5,000 rows per load; what a cut cascade didn't deliver loads when it's read. Eager children of an eager model arrive at startup, so here every todo's comments would load when the app opens: use it where the children stay few. ## Server queries: rows that aren't on the device `where` filters the rows on the device. To search rows that aren't there, such as every comment in a large project, ask the server with `query`: ```tsx title="src/app/CommentSearch.tsx" import { live } from "@clientdb/react"; import { db } from "@/sync/db"; export const CommentSearch = live(({ text }: { text: string }) => { const results = db.comment.query({ where: { body: { contains: text, mode: "insensitive" } }, orderBy: ["createdAt", "desc"], limit: 20, }); return (
    {results.status === "loading" &&

    Searching…

    } {results.all.map((comment) => { return

    {comment.body}

    ; })} {results.hasMore && ( )}
    ); }); ``` The server's answer is merged with what's already on the device, in order, cut to the pages loaded. Its rows become ordinary rows on the device, with their eager children. | `results.status` | Meaning | |---|---| | `"loading"` | the server hasn't answered, and nothing on the device matches yet | | `"partial"` | the server hasn't answered (or failed); matching rows already on the device are shown | | `"complete"` | the server answered; the result stays live with local changes, and `results.refresh()` asks again for rows that only started matching on the server | `query` takes the same `where` as local reads, an `orderBy` of one field and a direction (ties are ordered by id), and a `limit` per page. `loadMore()` loads the next page and `preload()` asks without reading the result; both resolve when the rows are on the device. A model can only be queried when its rules say which fields and operators `where` may use, and the largest page. Results are still limited to rows the viewer may read: ```ts title="src/sync/permissions/comment.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; export const commentRules = defineModelRules(schema, "comment", { read: (comment, $) => { return $.canRead(comment.todo); }, create: { when: (comment, $) => { return $.canRead(comment.todo); }, enforce: ($) => ({ authorId: $.viewer.id }), }, query: { fields: { body: ["contains"], authorId: ["is"], createdAt: ["gte", "lte"] }, maxLimit: 50, }, }); ``` A query on another field or operator, or a larger `limit`, is refused with `Forbidden`. ## Keeping memory in check: eviction A client that loads lazily keeps every row it loaded. For an app that browses far more data than it needs at once, such as an admin panel over every customer, cap it: ```ts title="src/sync/adminDb.ts" "use client"; import { createDatabaseClient } from "@clientdb/client"; import { schema } from "./schema"; export const adminDb = createDatabaseClient({ schema, url: "/api/admin/sync", load: "lazy", // no startup load: every model loads when it's read, eager ones included eviction: { maxRows: 50_000 }, }); ``` Past `maxRows`, the client drops the loads used longest ago, each as a whole: a todo's comments, a server query's pages, one load with its cascade. Collections that held those rows read as `"partial"` again and load them when read. What stays: - whatever is on screen: every row an observed collection, server query or `get(id)` shows, every row whose fields a component reads (wherever the entity came from), and the loads that brought them, with their eager cascade; - eager models (with `load: "lazy"` on the client, nothing is eager); - rows with unsent writes or unsaved drafts. ## Archived rows Archivable models (`archivable: true` in the schema, or in `fromPrisma`'s `models`) can archive rows instead of deleting them. Default collections hide archived rows: ```ts import { db } from "@/sync/db"; db.todo.archived.all; // only archived db.todo.includeArchived().all; // both todo.isArchived; ``` See [Archive vs delete](/docs/server/archive-delete). ## Client state | Property | Meaning | |---|---| | `db.$viewer` | the signed-in user's own row, as verified by the server (`db.$viewer?.name`), or `null` | | `db.$session` | what the server verified: `viewerId`, `claims`, `readOnly` and `hasClaim(claim)` | | `db.$status` | `"bootstrapping"`, `"online"`, `"offline"`, `"outdated"` and so on | | `db.$pendingCount` | transactions not yet confirmed | | `db.$lastSyncId` | the last sync id applied | | `db.$groups` | the viewer's access groups ([under the hood](/docs/server/groups)) | | `db.$clientId` | this client's id (used to deduplicate resent transactions) | In React, wrap reads in `useLive(() => …)` (no dependency array) so the component re-renders only when the result changes, or render entities in `live()` components. With MobX, use `observer()` and read directly. See [React](/docs/client/reactivity). --- # Writing data > Create, update, edit-then-save, delete and server logic with $action. Every write is optimistic and returns a handle you can await. Every write changes the data on the user's device immediately and is sent to your server in the background. Each returns a `TransactionHandle`, so you can await the server's verdict when it matters and ignore it when it doesn't. The examples use the todo app from the [quick start](/docs/quick-start). ## Create ```ts import { db } from "@/sync/db"; const todo = db.todo.create({ projectId, authorId: db.$session.viewerId!, title: "Write release notes" }); // visible at once ``` - Omitted fields take their defaults. A missing required field throws a `Validation` error synchronously. - The `id` is generated on the device, a UUIDv7, so the entity has it at once. A model whose id is declared `t.uuid({ prefix: "pay" }).id()` (or `id: { prefix: "pay" }` in `fromPrisma`) gets ids such as `pay_01932c…`. You may pass an `id` yourself. - Fields Postgres fills in (`.generated()`, or `@default(autoincrement())` with Prisma) can't be written: they're left out of the create and update types, and arrive with the server's row. - Rules never fill in a field: when a rule `enforce`s `authorId: $.viewer.id`, pass it yourself, as above. ## Update ```ts import type { Todo } from "@/sync/db"; export async function rename(todo: Todo, title: string) { const handle = todo.update({ title }); await handle.confirmed; // resolves when the server confirms, rejects with a TransactionError if it refuses } ``` The server checks an update against the model's `update` rules. Rules can give different fields to different people, as [field groups](/docs/server/permissions): any member may change `title` and `done`, only an admin `isPrivate`. An update that changes fields from several groups needs every one of them to allow it; otherwise it's refused as a whole, and the error names the field that wasn't allowed. ## Edit, then save or revert Assigning a field records a draft: the entity shows the new value, but nothing is sent until you save. This suits forms. ```ts import type { Todo } from "@/sync/db"; export function editTitle(todo: Todo, title: string) { todo.title = title; todo.isDirty; // true todo.dirtyFields; // ["title"] } export function saveOrRevert(todo: Todo, save: boolean) { if (save) { todo.save(); // one transaction with the changed fields (or null if nothing changed) } else { todo.revert(); // drops the draft } } ``` `todo.set({ … })` assigns several fields at once. Saving is explicit by default; `createDatabaseClient({ schema, autoSave: "microtask" })` saves field assignments automatically. ## Delete A hard delete removes the row and applies each referencing relation's `onDelete`: rows whose relation says `"cascade"` are deleted with it, `"setNull"` references are cleared, and a `"restrict"` reference refuses the delete: ```ts import type { Todo } from "@/sync/db"; export async function remove(todo: Todo) { const { handle, undoable, unloadedDescendants } = todo.delete(); // gone from the screen at once todo.isDeleted; // true return { handle, undoable, unloadedDescendants }; } export async function removeUndoably(todo: Todo) { await todo.delete({ ensureUndoable: true }); // loads cascading comments not on the device first, then deletes } ``` Deletes can be undone, restoring the subtree with the original ids. Undo is only complete if the subtree was on the device, which `undoable` reports: a todo's comments are lazy, so they may not be. `ensureUndoable: true` fetches what's missing before deleting, so the row disappears after that round trip instead of at once. Models declared with `archivable: true` can also be archived (`todo.archive()`, `todo.unarchive()`, `todo.isArchived`): hidden everywhere, kept in the database. See [Archive vs delete](/docs/server/archive-delete). ## The transaction handle ```ts import type { TransactionRejection } from "@clientdb/client"; interface TransactionHandle { readonly id: string; readonly status: "pending" | "sent" | "confirmed" | "rejected"; readonly sent: Promise; readonly confirmed: Promise; // rejects with TransactionError readonly rejection: TransactionRejection | null; } ``` Writes are batched per microtask; `db.$flush()` sends them now. To send several writes as one atomic transaction, see [Transactions and undo](/docs/client/transactions). ## Server logic with `$action` clientdb doesn't run business logic on the server for you. Logic that must run there (charging a card, sending an email, checks across many rows) stays in your own server actions, tRPC procedures or API routes, writing with Prisma. The [triggers](/docs/guides/untracked-rows) bring those writes to every device. Wrap the call in `db.$action`. It runs your function, then waits for a sync that started after the function returned, so the rows it wrote are on this device when the promise resolves: ```tsx title="src/app/projects/InviteButton.tsx" "use client"; import { db } from "@/sync/db"; import { inviteTeammate } from "./actions"; // a server action: writes the member with Prisma, sends the email export function InviteButton({ projectId, email }: { projectId: string; email: string }) { return ( ); } ``` It resolves to your function's result and rejects with its error. If only the sync afterwards fails, it still resolves: the client retries in the background and reports the error through `$status` and `onError`. To show the outcome before the server answers, pass `optimistic`. The writes inside it change rows on this device only: never sent, stored or undoable. They're undone if your function fails, and replaced by the synced rows once they arrive: ```ts title="src/app/projects/completeAll.ts" import { db, type Todo } from "@/sync/db"; import { completeTodos } from "./actions"; // a server action that marks the todos done and notifies the project export function completeAll(todos: readonly Todo[]) { return db.$action( () => { return completeTodos(todos.map((todo) => todo.id)); }, { optimistic: () => { for (const todo of todos) { todo.update({ done: true }); } }, }, ); } ``` `optimistic` also receives the client with its write methods (`optimistic: (db) => { … }`), so a read-only client can show a preview too. ## Read-only clients A client created with `readOnly: true` only reads: its types have no `create`, `update`, `delete`, drafts, transactions or undo, and a write that gets through anyway throws a `ReadOnlyError` before anything changes. Use it for screens that must never write, such as an admin panel that browses every customer: ```ts title="src/sync/adminDb.ts" "use client"; import { createDatabaseClient } from "@clientdb/client"; import { schema } from "./schema"; export const adminDb = createDatabaseClient({ schema, url: "/api/admin/sync", readOnly: true }); ``` A session can be read-only too: when your server's `session()` callback returns `readOnly: true` (a suspended account, say), the server refuses its writes, and `db.$session.readOnly` turns `true`, so the client throws `ReadOnlyError` instead of showing writes the server would undo. ## Custom entity classes Entity classes are generated at runtime from the schema, with field accessors and relations on a shared prototype, and rows stored compactly as arrays. Extend them with ordinary classes: ```ts title="src/sync/db.ts" "use client"; import { Model, createDatabaseClient } from "@clientdb/client"; import { schema } from "./schema"; export class Todo extends Model(schema, "todo") { get isMine() { return this.authorId === db.$session.viewerId; } toggle() { return this.update({ done: !this.done }); } } export const db = createDatabaseClient({ schema, models: { todo: Todo } }); // Makes relations return your classes everywhere (project.todos → Todo[]). List the same classes here and in // `models`: a class in only one of them is a type error, since relations and db.todo would disagree. declare module "@clientdb/client" { interface Register { schema: typeof schema; models: { todo: Todo }; } } ``` Instances are created by the client (`db.todo.create(…)`), never with `new`. Getters on custom classes are reactive like everything else. --- # Transactions and undo > Group writes into one atomic server transaction, undo and redo them, and handle rejections. ## Transactions Wrap several writes in `db.$transaction` to send them as one atomic server transaction. Either all apply or none do. The examples use the todo app from the [quick start](/docs/quick-start). ```ts title="src/app/projects/splitTodo.ts" import { db, type Todo } from "@/sync/db"; export async function splitTodo(todo: Todo, secondTitle: string) { const viewerId = db.$session.viewerId; if (!viewerId) { throw new Error("Not signed in"); } const handle = db.$transaction(() => { const second = db.todo.create({ projectId: todo.projectId, authorId: viewerId, title: secondTitle }); db.comment.create({ todoId: second.id, authorId: viewerId, body: `Split from "${todo.title}"` }); todo.update({ title: `${todo.title} (part 1)` }); }); await handle.confirmed; } ``` Writes outside `db.$transaction` are still transactions, one per call. ## Undo and redo The client keeps a local history of this client's transactions. ```ts import { db } from "@/sync/db"; db.$undo(); // UndoResult | null db.$redo(); db.$canUndo; // reactive db.$canRedo; db.$undoGroup(() => { // several transactions as one undo step todo.update({ done: true }); otherTodo.update({ done: true }); }); ``` - **Undo sends inverse transactions.** Undoing a hard delete restores the subtree with its original ids. - **It respects other people's work.** A field someone else changed in the meantime is left alone and reported in `UndoResult.skipped`. - **Rejected transactions leave the stack.** If the server refuses a transaction, its undo entry is removed. - The stack holds 100 entries by default; set `undoLimit` on the client to change it. ```ts import { db } from "@/sync/db"; const result = db.$undo(); for (const { model, id, field } of result?.skipped ?? []) { console.log(`${model} ${id}: ${field} was changed by someone else; left as is`); } ``` ## Rejections If the server refuses a transaction, the whole transaction is dropped from the pending stack, so its optimistic changes disappear. Then: - `handle.confirmed` rejects with a `TransactionError`; - the client's `onTransactionError` option and every `db.$onTransactionError(listener)` are called; - its undo entry is removed. Rejections are never silent. When nothing handles one (no `onTransactionError`, no listener, and nobody awaited `confirmed`), the client logs it: always in development, and `Forbidden`, `Validation` and `Stale` rejections in production too. So a wrong permission rule shows up in the console instead of as "my checkbox unticks itself". To show them to users, listen where your UI lives. In React: ```tsx title="src/app/TransactionErrorToasts.tsx" "use client"; import { useTransactionErrors } from "@clientdb/react"; import { toast } from "@/components/toast"; export function TransactionErrorToasts() { useTransactionErrors((rejection) => { toast.error(`${rejection.code}: ${rejection.message}`); }); return null; } ``` Render it inside `DatabaseProvider`. Outside React, `const stop = db.$onTransactionError((rejection) => { … })` returns an unsubscribe function, and the `onTransactionError` option of `createDatabaseClient` does the same for the client's whole life. | Code | Meaning | |---|---| | `Forbidden` | a write rule refused it, or an update changed a field no group of the `update` rules allows; the message names the branches that failed, e.g. `Forbidden: todo.delete (author: no, admin: no)` | | `ReadOnly` | the session is read-only: the route says `readOnly: true`, `session()` returned it, or the session is anonymous | | `Validation` | unknown field or model, a missing required field, a `validate()` error, a generated field or a changed primary-key field | | `Conflict` | create with an existing id, or a delete restricted by references | | `NotFound` | update or delete of a row that doesn't exist, or that the viewer can't read | | `AccessLost` | the client lost read access to a row it had unsent writes on (issued locally on eviction; the whole transaction is refused, including its writes to rows it still reads). A transaction already sent is left to the server's answer | | `SchemaOutdated` | the client's schema hash differs from the server's | ## At most once Unconfirmed transactions are kept and resent after reconnects, and across reloads when [storage](/docs/storage) is enabled. The server deduplicates them by `(clientId, clientTransactionId)`, so each applies once. It keeps those ids for `retention.transactions` (90 days by default); a transaction resent after its id was deleted, which the server may have applied, is rejected with `Stale` instead of applied twice (see [At most once](/docs/server/conflicts#at-most-once)). --- # React: keeping components up to date > Built-in fine-grained signals with useLive, or MobX-native observability with one option. Same types either way. Every entity field, relation, collection, load status and dirty flag is reactive. Reactivity is allocated lazily, per field and per query, so a 100,000-row replica costs nothing until you observe it. ## Built-in signals (default) With no options, the client uses its own fine-grained signals. The examples use the todo app from the [quick start](/docs/quick-start). `@clientdb/react` gives you two ways to subscribe a component: | | Tracks | Use it for | |---|---|---| | `useLive(fn)` | only what `fn` reads | picking data: lists, counts, lookups | | `live(Component)` | everything the component reads while rendering | components that render entity fields and relations, such as list rows | ### `useLive` ```tsx title="src/app/projects/OpenTodos.tsx" "use client"; import { useLive } from "@clientdb/react"; import type { Project } from "@/sync/db"; export function OpenTodos({ project }: { project: Project }) { const titles = useLive(() => { return project.todos.where({ done: false }).orderBy("updatedAt", "desc").all.map((todo) => todo.title); }); const count = useLive(() => { return project.todos.count; }); return (

    {project.name} · {titles.length} of {count} open

      {titles.map((title, index) => { return
    • {title}
    • ; })}
    ); } ``` `useLive(fn)` subscribes the component to whatever `fn` reads and re-renders only when the result changes. There is no dependency array: `fn` runs on every render, so it always sees the current props, and queries are cached by their filters, so running `db.todo.where({ projectId })` again finds the same live query. Expensive derivations belong in `db.$computed`. ### `live()` `useLive` tracks what its function reads, not what the component reads afterwards from the returned entities. Rendering `todo.title` or `todo.author.name` from a `useLive` result in the same component is a read nobody observes: the component keeps showing the first value. Wrap such components in `live()`: ```tsx title="src/app/projects/TodoList.tsx" "use client"; import { live, useLive } from "@clientdb/react"; import { db, type Todo } from "@/sync/db"; const TodoRow = live(({ todo }: { todo: Todo }) => { return (
  • {todo.title} · {todo.author?.name ?? "Unknown"} · {todo.done ? "done" : "open"}
  • ); }); export function TodoList({ projectId }: { projectId: string }) { const todos = useLive(() => { return db.todo.where({ projectId }).orderBy("updatedAt", "desc").all; }); return (
      {todos.map((todo) => { return ; })}
    ); } ``` `Todo` and `Project` are the entity types, exported from `src/sync/db.ts` as in the [quick start](/docs/quick-start#7-the-client): `type DB = EntitiesOf; export type Todo = DB["Todo"];`. `live(Component)` tracks every entity field, relation and collection read while rendering (like MobX `observer`) and memoizes the component on its props (shallow comparison, as `memo`). Only the row whose data changed re-renders. It is safe under StrictMode, supports hooks inside, and works with the MobX adapter too (through `DatabaseProvider`). ### The untracked-read warning In development, reading an entity field or relation during render outside `useLive` and `live()` logs a one-time warning per `model.property`: ```text clientdb: project.todos read during render outside useLive()/live(); this component won't update when it changes. Read it inside useLive(() => …), or wrap the component in live() (observer() with MobX). ``` Fix it by moving the read into `useLive`, or wrapping the component in `live()`. ## MobX Pass the MobX adapter, and everything becomes MobX-observable. Wrap components in `observer()` and read data directly: ```ts title="src/sync/db.ts" "use client"; import { createDatabaseClient, type EntitiesOf } from "@clientdb/client"; import { mobxReactivity } from "@clientdb/mobx"; import { schema, type Schema } from "./schema"; export const db = createDatabaseClient({ schema, reactivity: mobxReactivity() }); export type DB = EntitiesOf; export type Todo = DB["Todo"]; export type Project = DB["Project"]; ``` ```tsx title="src/app/projects/OpenTodos.tsx" "use client"; import { observer } from "mobx-react-lite"; import type { Project } from "@/sync/db"; export const OpenTodos = observer(function OpenTodos({ project }: { project: Project }) { return (
      {project.todos.where({ done: false }).all.map((todo) => { return
    • {todo.title}
    • ; })}
    ); }); ``` Don't use `useLive` inside `observer` components: with MobX reactivity it throws. The public types are identical with either reactivity. ## `DatabaseProvider` Wrap your app in `DatabaseProvider` once. With `ready`, it renders `fallback` until the eager models are usable, so components can read them right away (lazy models show their own loading state). It also gives `useLive` and `live()` the client's reactivity, MobX included: ```tsx title="src/app/providers.tsx" "use client"; import { DatabaseProvider } from "@clientdb/react"; import { Spinner } from "@/components/spinner"; import { db } from "@/sync/db"; export function Providers({ children }: { children: React.ReactNode }) { return ( }> {children} ); } ``` ## Outside React `db.$computed` and `db.$effect` work anywhere, with whichever reactivity the client uses: ```ts import { db } from "@/sync/db"; const titles = db.$computed(() => { return db.todo.all.map((todo) => { return todo.title; }); }); const stop = db.$effect(() => { console.log(titles.get()); }); ``` With a MobX client, MobX's own `computed` and `autorun` work too. ## Performance notes - Observed queries are maintained incrementally from the replica's change sets (O(log n) per affected query). Unobserved queries are computed on demand. - One observed field write, with a filtered collection watching that column, costs about 11–25 µs on 10k–100k rows. - Client memory is about 177 bytes per row. See [Benchmarks](/docs/reference/benchmarks). --- # Permissions > One file per model that says who may see and change what: read rules, restricted fields, write rules with field groups, server query rules and claims. In a usual app, every API route checks permissions on its own: "is this user a member of this project?", "only admins may rename it". With clientdb there are no per-feature routes, so those checks live in one place instead: a `permissions` folder with one file per model. It answers two questions for each model: - **Who may read it?** Each user's device only ever receives the rows their `read` rule allows. When the answer changes (someone joins a project, a todo turns private), clientdb adds or removes rows on their devices to match. - **Who may change it, and how?** Every write from a device is checked on your server against the `create`, `update`, `delete` and `archive` rules before it's saved. A refused write is undone on the user's screen. Rules are written in TypeScript and typed against your models and relations, so `todo.project.members` autocompletes and a typo is a compile error. The examples use the todo app from the [quick start](/docs/quick-start), with one addition: each project has an invite code that only its admins receive. ```ts title="src/sync/schema.ts" import { fromPrisma } from "@clientdb/prisma"; import { prismaModels } from "../generated/clientdb"; export const schema = fromPrisma(prismaModels, { omit: { User: ["passwordHash"] }, models: { User: { load: "eager" }, Project: { load: "eager", restricted: ["inviteCode"] }, Member: { load: "eager" }, Todo: { load: "eager" }, }, }); export type Schema = typeof schema; ``` ## One file per model A rule receives the row and `$`, the permission helpers: `$.viewer.id` is the signed-in user, and `$.anyOf`, `$.and` and the others combine conditions. Nothing is shared between files except what you import. Conditions you reuse across models are defined once with `defineRule`, next to the model they're about. The row's type comes from the model name: ```ts title="src/sync/permissions/project.ts" import { defineModelRules, defineRule } from "@clientdb/server"; import { $support } from "../claims"; import { schema } from "../schema"; export const isMember = defineRule(schema, "project", (project, $) => { return project.members.some((member) => { return member.userId.is($.viewer.id); }); }); export const isAdmin = defineRule( schema, "project", (project, $) => { return project.members.some((member) => { return $.and(member.userId.is($.viewer.id), member.role.is("admin")); }); }, { name: "project.admin" }, // optional: a readable, stable id for a widely shared condition ); export const projectRules = defineModelRules(schema, "project", { read: { when: (project, $) => { return $.anyOf({ member: isMember(project), support: $support }); }, fields: { inviteCode: (project) => { return isAdmin(project); }, }, }, create: { when: (project, $) => { return $.authenticated; }, }, update: { when: (project) => { return isAdmin(project); }, fields: ["name", "inviteCode"], }, archive: { when: (project) => { return isAdmin(project); }, }, }); ``` Other models import the conditions they need: ```ts title="src/sync/permissions/todo.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; import { isAdmin, isMember } from "./project"; export const todoRules = defineModelRules(schema, "todo", { read: (todo, $) => { return $.anyOf({ shared: [todo.isPrivate.is(false), isMember(todo.project)], author: todo.authorId.is($.viewer.id), admin: isAdmin(todo.project), }); }, create: { when: (todo) => { return isMember(todo.project); }, enforce: ($) => ({ authorId: $.viewer.id }), }, update: [ { fields: ["title", "done"], when: (todo) => { return isMember(todo.project); }, }, { fields: ["isPrivate"], when: (todo, $) => { return $.anyOf({ author: todo.authorId.is($.viewer.id), admin: isAdmin(todo.project) }); }, }, ], delete: { when: (todo, $) => { return $.anyOf({ author: todo.authorId.is($.viewer.id), admin: isAdmin(todo.project) }); }, }, // what server queries (`db.todo.query(…)`) may filter on, and the largest page query: { fields: { title: ["contains", "startsWith"], done: ["is"], createdAt: ["gte", "lt"] }, maxLimit: 100, }, }); ``` ```ts title="src/sync/permissions/member.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; import { isAdmin, isMember } from "./project"; export const memberRules = defineModelRules(schema, "member", { read: (member) => { return isMember(member.project); }, // no create rule: invitations are accepted by a server action, which writes the member row update: { when: (member) => { return isAdmin(member.project); }, fields: ["role"], }, delete: { when: (member, $) => { return $.anyOf({ admin: isAdmin(member.project), leaving: member.userId.is($.viewer.id) }); }, }, }); ``` ```ts title="src/sync/permissions/comment.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; // a comment is readable exactly when its todo is export const commentRules = defineModelRules(schema, "comment", { read: (comment, $) => { return $.canRead(comment.todo); }, create: { when: (comment, $) => { return $.canRead(comment.todo); }, enforce: ($) => ({ authorId: $.viewer.id }), }, delete: { when: (comment, $) => { return comment.authorId.is($.viewer.id); }, }, }); ``` `user` follows the same pattern: a user reads their own row and their teammates' (see the [quick start](/docs/quick-start#3-permissions-server-only)). Finally, one file combines them: ```ts title="src/sync/permissions/index.ts" import { definePermissions } from "@clientdb/server"; import { schema } from "../schema"; import { commentRules } from "./comment"; import { memberRules } from "./member"; import { projectRules } from "./project"; import { todoRules } from "./todo"; import { userRules } from "./user"; export const permissions = definePermissions(schema, [userRules, projectRules, memberRules, todoRules, commentRules]); ``` A module works too: `definePermissions(schema, modelRules)`, after `import * as modelRules from "./rules"`, takes every rule set it exports and ignores the rest (such as `isMember`). `definePermissions` refuses two rule sets for one model, and rule sets or conditions built from another schema. Outside production it is also strict: a model with no read rule is an error that names it, so a new model can't silently stay off devices. Nothing is readable implicitly, not even a child that cascades from its parent: `comment` says `$.canRead(comment.todo)` itself. Mark models that never sync `serverOnly` in the schema, or pass `{ strict: false }` to let models without a read rule simply not sync. ## Rule shapes | Rule | Shape | Meaning | |---|---|---| | `read` | `(row, $) => condition` | which viewers receive the row. Without it, the model never syncs | | `read` | `{ when, fields: { inviteCode: (row, $) => condition } }` | the form for models with [restricted fields](#restricted-fields) | | `create` | `{ when, enforce? }` | who may create rows; `enforce` lists fields that must equal a value | | `update` | `{ when, fields }`, or a list of them | who may change which fields ([field groups](#update-field-groups)) | | `delete` | `{ when }` | who may delete rows | | `archive` | `{ when }` | who may archive and unarchive rows of an [archivable](/docs/server/archive-delete) model | | `query` | `{ fields, maxLimit }` | what [server queries](#server-queries) may filter on | | `validate` | `async ({ operation, before, after, viewer, db }) => message \| null` | any check, in the write's transaction; return a message to refuse | - **A missing write rule refuses that operation.** No `delete` rule: nobody deletes from a device; your backend still can. - **`when` must hold before and after the change**, for updates, so nobody can move a row out of their reach or into someone else's. - **`enforce`** lists fields that must equal `$.viewer.id` or a literal: `enforce: ($) => ({ authorId: $.viewer.id, status: "open" })`, or `enforce: { status: "open" }` without the viewer. It applies to every row the viewer creates, and to updates that change those fields. A write with another value is refused with `Forbidden`, naming the field: `todo.authorId must equal the viewer's id`. Rules only check, they never fill anything in: the device sends `authorId: db.$session.viewerId` itself, so the right value shows at once. - **`validate`** is for what conditions can't express, such as "at most 50 todos per project". `viewer` is the viewer's id, and `db.find(model, field, value)` reads rows. ### Update field groups `update` takes a list of field groups, each with its own condition. In `todoRules` above, any member may change `title` and `done`; only the author or an admin may change `isPrivate`. An update passes when every field it changes belongs to a group whose `when` holds, before and after the change. A member who isn't the author and changes `done` and `isPrivate` together is refused as a whole, and the error names `isPrivate`. `updatedAt` fields belong to every group. One group needs no list: `update: { when, fields }`. ### Restricted fields A read rule decides which rows a viewer receives. A restricted field narrows that for one field: the viewer receives the row when `when` holds, and the field's value only when its own rule holds too. Everyone else receives the row without it. - Declare the field restricted in the schema: `.restricted()` in TypeScript, `restricted: ["inviteCode"]` in `fromPrisma`. - Then the model's read rule takes the `{ when, fields }` form, and every restricted field needs a rule there. Only restricted fields take one: a field rule on any other field is a type error. - On the client, a restricted field is typed `T | undefined`: `project.inviteCode` is `undefined` on a plain member's device. - Viewers who can't read a field can't change it either. A restricted field can't be a load key or appear in `query.fields`: looking rows up by it could reveal it. - A restricted field with no rule in `fields` is an error from `definePermissions` outside production, and reaches nobody in production. When someone becomes an admin, the invite codes arrive on their devices; when they stop being one, the codes are removed. ### Server queries `db.todo.query({ where, orderBy, limit })` asks the server for rows that aren't on the device (see [Reading data](/docs/client/queries#server-queries-rows-that-arent-on-the-device)). A model can only be queried when its rules say how: - `fields` lists the fields `where` may filter on, each with its operators: `is`, `in`, ranges (`gt`, `gte`, `lt`, `lte`), and on text `contains`, `startsWith` and `endsWith`. A query on another field or operator is refused with a `QueryError` that names it. - `maxLimit` is the largest page a query may ask for. - Results are still limited to rows the viewer may read, so `query` never widens access; it only says which searches are allowed. ## Claims: facts about the session A claim is a fact about the signed-in session that isn't a row, such as "has an active support login". Declare it once, in a file the server and the client both import: ```ts title="src/sync/claims.ts" import { declareClaim } from "@clientdb/schema"; export const $support = declareClaim("support"); ``` - Your [session callback](/docs/transports/http#the-session) grants it: `claims: [$support(isOnShift)]` (the claim is granted when the argument is true, the default). - A rule uses it as a condition anywhere: alone, in `$.anyOf`, `$.and` and `$.or`. In `projectRules` above, support staff read every project. - The client asks for it: `db.$session.hasClaim($support)`. clientdb checks the session again on every request, and on a live connection every few minutes. When the callback stops granting a claim, the rows readable only through it leave that device. See [Permission recipes](/docs/guides/permission-recipes#staff-and-other-facts-about-the-session). ## The rule language Fully typed through your relations: | Expression | Meaning | |---|---| | `row.field.is(value)`, `.is($.viewer.id)` | equality | | `.isNot(value)`, `.in([…])`, `.notIn([…])` | comparisons with literals | | `.isNull()`, `.notNull()` | null checks | | `row.flag`, `row.flag.is(false)` | a boolean field used directly, or its negation | | `row.relation.field` | follows to-one relations: `todo.project.name` | | `row.collection.some((child) => { … })` | a matching child row exists: `project.members.some(…)` | | `$.anyOf({ label: condition, other: [a, b] })` | "or" with labeled branches; an array means all of its conditions must hold | | `$.and(a, b)`, `$.or(a, b)` | unlabeled "and" and "or" | | `$staff` (a claim) | the session holds the claim | | `$.authenticated` | every signed-in viewer | | `$.public` | everyone, anonymous visitors included | | `$.canRead(row.relation)` | the related row's own read rule: `$.canRead(comment.todo)`. Works in read and write rules; see [below](#reading-like-the-parent) | | `$.canRead(row.relation, { except: ["admin"] })` | that read rule without some labeled branches or named rules | | `defineRule(schema, "project", (project, $) => { … }, { name })` | a reusable condition, called as `isMember(todo.project)` | | `$.named("project.member", condition)` | gives a condition a stable, readable id, as `defineRule`'s `name` does | | `$.viewer.row.field` | the viewer's own fields: `$.viewer.row.email.is("…")` | | `$.group("auditors")`, `$.group("guests", todo.projectId)` | an [explicit group](/docs/server/groups#explicit-groups) | | `$.not(condition)` | only for [deny rules](#deny-rules) | The labels in `$.anyOf` show up in `explain()` and in errors, so a refused write says which branches failed: ```text Forbidden: todo.delete (author: no, admin: no) ``` ## Reading like the parent `$.canRead(row)` holds when the viewer may read that row under its own model's read rule. It takes a row reached from the rule's row: a relation (`comment.todo`, `comment.todo.project`), a row inside `some()`, or the rule's row itself, which suits write rules (`$.canRead(comment)`: the writer must be able to read what they write). A read rule that is exactly `$.canRead(parent)` makes each row readable by whoever can read its parent: ```ts read: (comment, $) => { return $.canRead(comment.todo); }, ``` The engine stores such rows with their parent's access. When the parent's access changes, for example when a todo with 2,000 comments becomes private, the children are re-tagged in bulk, one `UPDATE … RETURNING` per level, and users who lose the todo lose its comments with it. A child with [restricted fields](#restricted-fields), a rule with `except`, or a rule that adds conditions (`$.and($.canRead(comment.todo), …)`) still works; its rows are routed one by one instead. `$.canRead` is independent of [`onDelete: "cascade"`](/docs/schema#cascading-relations): a cascading child needs a read rule like any other model, and a child that doesn't cascade can read like its parent too. ## Why some read rules are rejected clientdb has to know, for every change, which users should receive it, without running your rules once per user. So read rules must describe access in terms of **who the user is related to**: a project they're a member of, a todo they wrote, their own user row, a claim they hold. Rules are checked when the server starts; a rule that can't be turned into "these users may see this row" fails right away with `AccessCompileError` and a message that says why, instead of leaking data later. Write rules have no such limit: they run on the server for each write, so they can check anything. The full list of rejected shapes, and how clientdb turns rules into deliveries, is in [Under the hood: groups and routing](/docs/server/groups). ## Every signed-in user, and anonymous visitors Every read branch needs a condition on the viewer. A rule like `read: (todo) => { return todo.isPrivate.is(false); }` would let every signed-in user of the app read every public todo, so it is a compile error. Say so explicitly when that is what you mean: ```ts read: (todo, $) => { return $.and($.authenticated, todo.isPrivate.is(false)); // any signed-in user, never anonymous }, ``` `$.public` includes anonymous visitors too. When your session callback returns `null` and the handler sets `anonymous: true`, the request gets an anonymous, read-only session that sees only `$.public` rows. Without `anonymous: true`, `null` is answered with 401. ## Deny rules `$.not` is only for rules that withhold a row whatever else allows it, such as a block list: `$.and($.not(blockedByViewer), isMember(todo.project))`. See [Deny lists](/docs/guides/permission-recipes#deny-lists). Everywhere else, negate a field with `.is(false)`. ## Testing your rules `compileAccess(permissions).explain()` prints how clientdb understood your rules, branch labels included. To check what each user actually receives and which writes are refused, see [Testing](/docs/guides/testing). clientdb's own test suite checks the engine against a reference implementation of the rules: after any sequence of changes, every simulated user must hold exactly what the rules allow. --- # Permission recipes > Copy-paste read and write rules for the common shapes: team membership, roles, owner-only, inherited access, public and signed-in data, staff claims, restricted fields and deny lists. Each recipe is a `defineModelRules(schema, "model", { … })` call that lives in that model's file and is combined with the others by `definePermissions(schema, [...])` (see [Permissions](/docs/server/permissions)). Read rules describe access through who the user is related to (see [why some read rules are rejected](/docs/server/permissions#why-some-read-rules-are-rejected)); write rules can check anything. The recipes share one app: teams with members, projects and issues. The conditions they reuse live in the team's file: ```ts title="src/sync/permissions/team.ts" import { defineRule } from "@clientdb/server"; import { schema } from "../schema"; export const isMember = defineRule( schema, "team", (team, $) => { return team.members.some((member) => { return member.userId.is($.viewer.id); }); }, { name: "team.member" }, ); export const isAdmin = defineRule( schema, "team", (team, $) => { return team.members.some((member) => { return $.and(member.userId.is($.viewer.id), member.role.in(["owner", "admin"])); }); }, { name: "team.admin" }, ); ``` ## Team membership ```ts title="src/sync/permissions/project.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; import { isMember } from "./team"; export const projectRules = defineModelRules(schema, "project", { read: (project) => { return isMember(project.team); }, create: { when: (project) => { return isMember(project.team); }, }, update: { when: (project) => { return isMember(project.team); }, fields: ["name"], }, }); ``` Adding someone to a team (a new `teamMember` row) sends them the team's data; removing them takes it off their devices. ## Roles, and fields only some roles may change ```ts title="src/sync/permissions/issue.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; import { isAdmin, isMember } from "./team"; export const issueRules = defineModelRules(schema, "issue", { read: (issue, $) => { return $.anyOf({ visible: [issue.hidden.is(false), isMember(issue.team)], hidden: [issue.hidden, isAdmin(issue.team)], }); }, update: [ { fields: ["title", "done"], when: (issue) => { return isMember(issue.team); }, }, { fields: ["hidden"], when: (issue) => { return isAdmin(issue.team); }, }, ], }); ``` `update` takes 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 may rename an issue, only an admin may hide it, and a member's update that touches `hidden` is refused as a whole. When someone is promoted or demoted, admin-only rows appear on or disappear from their devices automatically. Use `in([...])` for several roles inside one rule function, not `$.or` of two `is`. ## Owner only ```ts title="src/sync/permissions/draft.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; export const draftRules = defineModelRules(schema, "draft", { read: (draft, $) => { return draft.authorId.is($.viewer.id); }, create: { when: (_draft, $) => { return $.authenticated; }, enforce: ($) => ({ authorId: $.viewer.id }), }, update: { when: (draft, $) => { return draft.authorId.is($.viewer.id); }, fields: ["body"], }, delete: { when: (draft, $) => { return draft.authorId.is($.viewer.id); }, }, }); export const notificationRules = defineModelRules(schema, "notification", { read: (notification, $) => { return notification.userId.is($.viewer.id); }, }); ``` `enforce` means "must equal": the client creates drafts with `authorId: db.$session.viewerId`, and a draft created with anyone else's id is rejected with `Forbidden: draft.authorId must equal the viewer's id (got …)`. `authorId` isn't in any update group, so nobody can hand a draft to someone else either. ## Children inherit their parent's access A child that is readable whenever its parent is says so with `$.canRead`, whether or not it [cascades](/docs/schema#cascading-relations) from that parent. Nothing is readable implicitly, so every synced child has a read rule: ```ts title="src/sync/permissions/comment.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; export const commentRules = defineModelRules(schema, "comment", { read: (comment, $) => { return $.canRead(comment.issue); }, create: { when: (comment, $) => { return $.canRead(comment.issue); }, enforce: ($) => ({ authorId: $.viewer.id }), }, }); // attachments are never written by clients: a read rule is all they need export const attachmentRules = defineModelRules(schema, "attachment", { read: (attachment, $) => { return $.canRead(attachment.comment); }, }); ``` When the parent is hidden or moved, its children follow it, re-tagged in bulk. Use `$.canRead(comment.issue, { except: ["hidden"] })` to reuse a rule without some labeled branches (here, the admins-only branch of the issue rule); such a rule is routed row by row instead of re-tagged in bulk. ## Users who share a team ```ts title="src/sync/permissions/user.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; import { isMember } from "./team"; export const userRules = defineModelRules(schema, "user", { read: (user, $) => { return $.anyOf({ self: user.id.is($.viewer.id), teammate: user.memberships.some((membership) => { return isMember(membership.team); }), }); }, }); ``` ## Every signed-in user ```ts title="src/sync/permissions/announcement.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; export const announcementRules = defineModelRules(schema, "announcement", { read: (announcement, $) => { return $.and($.authenticated, announcement.draft.is(false)); }, }); ``` A branch with no viewer condition, like `announcement.draft.is(false)` alone, is a compile error; `$.authenticated` makes the intent explicit. ## Public, including anonymous visitors ```ts title="src/sync/permissions/post.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; import { isMember } from "./team"; export const postRules = defineModelRules(schema, "post", { read: (post, $) => { return $.anyOf({ published: [post.published, $.public], team: isMember(post.team), }); }, }); ``` Anonymous sessions (your `session(request)` callback returns `null` and the handler sets `anonymous: true`) are read-only and see only `$.public` rows. ## Staff and other facts about the session Some access depends on the login, not on rows: an active staff session, a verified email, a paid plan your auth provider knows about. Declare each such fact once as a claim, in a file both server and client import: ```ts title="src/sync/claims.ts" import { declareClaim } from "@clientdb/schema"; export const $staff = declareClaim("staff"); ``` Your `session()` callback grants it, per request: ```ts title="src/app/api/sync/[...path]/route.ts" import { clientdbHandler } from "@clientdb/server/next"; import { getSession } from "@/lib/auth"; import { $staff } from "@/sync/claims"; import { engine } from "@/sync/engine"; export const { GET, POST } = clientdbHandler(engine, { session: async (request) => { const session = await getSession(request); if (!session) { return null; } return { viewer: session.userId, claims: [$staff(session.isStaff)] }; }, }); ``` Rules use it like any other condition: ```ts title="src/sync/permissions/ticket.ts" import { defineModelRules } from "@clientdb/server"; import { $staff } from "../claims"; import { schema } from "../schema"; import { isMember } from "./team"; export const ticketRules = defineModelRules(schema, "ticket", { read: (ticket, $) => { return $.anyOf({ team: isMember(ticket.team), staff: $staff, }); }, }); ``` On the client, `db.$session.hasClaim($staff)` tells the UI whether to show the staff tools. A claim can't be negated or combined with viewer conditions in one branch; give it its own branch, as above. When a session loses a claim, the rows it granted leave the device on the next sync. A fact that is a column of the user's own row works too: `$.viewer.row.role.in(["support"])` compares the viewer's row with fixed values, and changing the column updates what they see. ## Fields only some users may see Mark the field `.restricted()` in the schema (or list it under `restricted` in `fromPrisma`). The model's read rule then becomes `{ when, fields }`: everyone `when` allows receives the row, and each restricted field reaches only the people its own rule allows. Others get the row without it. ```ts title="src/sync/permissions/user.ts" import { defineModelRules } from "@clientdb/server"; import { $staff } from "../claims"; import { schema } from "../schema"; import { isMember } from "./team"; // in the schema: email: t.string().unique().restricted() export const userRules = defineModelRules(schema, "user", { read: { when: (user, $) => { return $.anyOf({ self: user.id.is($.viewer.id), teammate: user.memberships.some((membership) => { return isMember(membership.team); }), }); }, fields: { email: (user, $) => { return $.anyOf({ self: user.id.is($.viewer.id), staff: $staff, }); }, }, }, }); ``` On a device without access, `user.email` is `undefined` (the type says so), and a restricted field can't be a load key or a server-query filter. A restricted field with no rule in `fields` is an error from `definePermissions` outside production, and reaches nobody in it. ## Deny lists ```ts title="src/sync/permissions/document.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; import { isMember } from "./team"; export const documentRules = defineModelRules(schema, "document", { read: (document, $) => { const blocked = document.blocks.some((block) => { return block.userId.is($.viewer.id); }); return $.and($.not(blocked), isMember(document.team)); }, }); ``` A whole-rule deny withholds the row from blocked users even when another branch allows it. Blocking and unblocking move the row out and back in for that user. This is the one place to use `$.not`; elsewhere, negate a field with `.is(false)`. ## Rules that need data the router can't see Use an [explicit group](/docs/server/groups#explicit-groups) with your own membership function, or a `validate` function for write-side checks such as uniqueness or quotas: ```ts title="src/sync/permissions/inviteLink.ts" import { defineModelRules } from "@clientdb/server"; import { schema } from "../schema"; import { isMember } from "./team"; export const inviteLinkRules = defineModelRules(schema, "inviteLink", { create: { when: (link) => { return isMember(link.team); }, }, validate: async ({ operation, after, db }) => { if (operation !== "create") { return null; } const links = await db.find("inviteLink", "teamId", after!.teamId); return links.length >= 50 ? "Link limit reached" : null; }, }); ``` --- # Writes made outside clientdb > Rows your app writes outside clientdb (Prisma Client, seed scripts, SQL, other services) reach clients through Postgres triggers, with engine.reconcile() as the safety net. On Prisma-managed tables, clientdb keeps sync metadata for each row in a side table (`clientdb_row`): the last copy it sent to clients, and its routing groups. Writes from browsers go through clientdb, so it always knows about them. Writes your server makes directly need one more piece, so clientdb learns which rows changed. The examples use the todo app from the [quick start](/docs/quick-start). ## Where they come from - server actions, tRPC routers, background jobs and admin tools that write with Prisma Client; - seed scripts and fixtures; - bulk SQL, backfills, manual fixes in a SQL console, and other services sharing the database. ## Default: Postgres triggers Generate a migration that adds change triggers to every synced table, and apply it like any other Prisma migration: ```bash npx clientdb-prisma triggers src/sync/schema.ts > prisma/migrations/20261202_clientdb_triggers/migration.sql npx prisma migrate dev ``` `triggers` reads your schema module (`--export name` if the schema isn't exported as `schema`) and covers every model it syncs, `serverOnly` ones included, since rules read those. It also drops the triggers of tables that no longer sync. From then on, every insert, update, delete and truncate on a synced table records the changed ids in a queue, in the same transaction as the write. The engine drains the queue on the next pull or push (or right away when `engine.start()` runs), reads the rows, and syncs them like writes from browsers. Your write code needs no clientdb calls: ```ts title="src/app/projects/actions.ts" "use server"; import { prisma } from "@/lib/prisma"; export async function addTodo(projectId: string, authorId: string, title: string) { await prisma.todo.create({ data: { projectId, authorId, title } }); } ``` - **Catches everything:** Prisma Client (nested writes and `createMany`/`updateMany`/`deleteMany` included), raw SQL, other services, `TRUNCATE`, updates that change a row's id, and rows Postgres or your own triggers changed in turn (`ON DELETE CASCADE`, `SET NULL`), including after writes from browsers. - **Atomic:** the queue entry commits or rolls back with your write. - **Same treatment as browser writes:** the rows reach every user who may see them, and the access changes they cause are applied. - **Run the command again when you add or remove a synced model**, into a new migration. Prisma ignores triggers, so `prisma migrate diff` reports no drift. The browser that called the action can wait for its rows with [`db.$action`](/docs/client/mutations#server-logic-with-action). ## Safety net: `engine.reconcile()` `engine.reconcile()` compares your tables with clientdb's last synced copies and syncs every difference: new rows, changed rows and deleted rows. ```ts title="scripts/clientdb-reconcile.ts" import { engine } from "@/sync/engine"; const reconciled = await engine.reconcile(); // { todo: 3 } console.log(reconciled); ``` - `clientdb migrate` runs it on every deploy, after adopting rows that were never tracked. Run it again after seeding a database before the triggers were installed. - Run it from a cron if some writes may bypass the triggers (for example while a trigger migration is pending). - It reads whole tables, a page at a time: fine for thousands of rows, slow for millions. Run it from a job, never per request. **Bulk changes: resync.** To send a whole model again, for example after a large backfill, use resync: ```ts import { engine } from "@/sync/engine"; await engine.resync("todo"); // one model await engine.resync(); // every synced model ``` Above `resyncInvalidateThreshold` (10,000 rows by default), clients receive one invalidation instead of the rows, and refetch the model. ## Only without triggers: `engine.changed` If you can't add triggers to your tables, tell the engine which rows you wrote. With the triggers installed, don't: they already do this. Model names are typed keys: ```ts title="src/app/projects/actions.ts" "use server"; import { prisma } from "@/lib/prisma"; import { engine } from "@/sync/engine"; export async function addTodo(projectId: string, authorId: string, title: string) { const todo = await prisma.todo.create({ data: { projectId, authorId, title } }); await engine.changed({ todo: [todo.id] }); } ``` To make it atomic with the write, call it inside the transaction: ```ts title="src/app/projects/moveTodo.ts" "use server"; import { prismaExecutor } from "@clientdb/prisma"; import { prisma } from "@/lib/prisma"; import { engine } from "@/sync/engine"; export async function moveTodo(todoId: string, projectId: string) { await prisma.$transaction(async (transaction) => { await transaction.todo.update({ where: { id: todoId }, data: { projectId } }); await engine.changed({ todo: [todoId] }, { transaction: prismaExecutor(transaction) }); }); } ``` Called after the transaction, a crash between the write and `engine.changed` leaves the row unsent until `engine.reconcile()` runs. Each write site must list every id it touched, including nested creates and `*Many` calls; triggers do this for you. ## The warnings In development, `clientdbHandler` and `createFetchHandler` check two things on their first request and warn once. Tables without triggers: ```text clientdb: writes to todo, comment made outside clientdb (Prisma Client, SQL) won't reach clients: their tables have no clientdb capture triggers. Save the output of `npx clientdb-prisma triggers` as a migration, or call engine.changed() after such writes. ``` And rows written outside clientdb that it has never tracked, so no client receives them: ```text clientdb: 3 todo rows are not tracked (written outside clientdb, e.g. by a seed script), so clients never receive them. Run engine.migrate() (or engine.reconcile()) to sync them, and capture future writes with the triggers from `npx clientdb-prisma triggers`. ``` The checks are on unless `NODE_ENV` is `production`. Turn them off with `warnUntracked: false`, for example in an app that deliberately uses `engine.changed`: ```ts title="src/app/api/sync/[...path]/route.ts" import { clientdbHandler } from "@clientdb/server/next"; import { getSyncSession } from "@/sync/session"; import { engine } from "@/sync/engine"; export const { GET, POST } = clientdbHandler(engine, { session: getSyncSession, warnUntracked: false }); ``` ## Checking from code ```ts import { engine } from "@/sync/engine"; await engine.untracked(); // [{ model: "todo", rows: 3 }]: rows never tracked await engine.uncaptured(); // ["comment"]: synced models whose table has no triggers ``` Both return an empty list on engine-owned tables, where every write goes through the engine. ## Summary | Situation | Fix | |---|---| | App code, scripts, SQL and other services writing to Prisma tables | the trigger migration (`npx clientdb-prisma triggers `) | | Rows written before the triggers existed, or any drift | `engine.reconcile()` (also runs in every `clientdb migrate`) | | Rows changed in bulk with SQL | `engine.resync(model)` or `engine.resync()` | | An app that can't use triggers | `engine.changed({ model: [ids] })`, inside the transaction for atomicity | | Not sure | `engine.untracked()` and `engine.uncaptured()`, or read the dev warnings | --- # Offline and multiple tabs > Keep the data and unsaved changes in the browser, so the app opens instantly and works offline, and let tabs share one connection. ## IndexedDB ```ts title="src/sync/db.ts" "use client"; import { createDatabaseClient, indexedDb } from "@clientdb/client"; import { schema } from "./schema"; export const db = createDatabaseClient({ schema, storage: indexedDb(), }); ``` `indexedDb()` needs no options. Each signed-in user gets their own copy automatically: the client stores the session the server last verified (viewer, claims, read-only) next to the data. If the server later reports a different viewer, the client deletes the local data and loads the new user's. A change of claims keeps the data: the server's next sync removes the rows the session can no longer read. On sign-out, call `await db.$clear()`. It deletes the local data and pending writes, so the next person on a shared computer doesn't inherit them. Every other open tab of the app drops its data too, and stops writing before the storage is cleared; each starts again, empty, on next use. **What's stored:** every row on the device as last confirmed by the server (the eager models, and the lazy rows loaded so far), how far it has synced, and every change not yet confirmed (so nothing is lost if the tab closes). Rows evicted from memory by [`eviction`](/docs/client/queries#keeping-memory-in-check-eviction) are removed from storage too. **On reload:** - the client starts offline-first: `db.$ready()` resolves from disk, before any network request, and lazy rows loaded before are there without a round trip; - it resumes from its stored sync id; - unsent writes are re-applied and resent, and the server deduplicates them. **After a schema change:** if a model's shape changed, only that model's rows are dropped and refetched (`GET …/bootstrap?models=…`) before the client resumes syncing. `db.$ready()` doesn't wait for the refetch. Until it succeeds, the model is marked stale on disk and the client retries with backoff, so a refetch that fails offline isn't lost. **Layout:** fixed, independent of your schema. The Swift client uses the same logical layout in SQLite. A clientdb release that changes the layout drops the stored rows and loads them again, but keeps the unsent changes. ## Multi-tab Multiple tabs work automatically whenever `storage` is set; there's no option for it. ```ts import { db } from "@/sync/db"; db.$role; // "leader" | "follower" ``` How it works: - Every tab saves its changes to the shared storage right away, so they survive the tab closing. - One tab is elected **leader** with Web Locks. It owns the connection and the stored rows, sends what the journal holds, and broadcasts server packets to the other tabs over `BroadcastChannel`. - Followers' `db.$sync()` calls go through the leader. - A tab that opens asks the leader for its rows, so it doesn't miss a packet the leader broadcast before the tab listened but hadn't stored yet. When the leader loads afresh (after the server lost its position, or another viewer signed in), followers replace their rows with the leader's in the same way. - When the leader tab closes, another tab takes over. Changes made in any tab survive both the tab closing and the handover. ## Offline behaviour - Reads of rows on the device always work: they come from memory. A lazy model's rows that were never loaded stay `loading` until the network is back. - Writes always work: they apply locally and wait until the network is back. (On a [read-only client](/docs/client/mutations#read-only-clients) they throw, online or not.) - `db.$status` is `offline` while the network is down; the client retries with backoff and reports errors through `onError`. - When access is lost while offline, transactions not yet sent that write rows evicted on reconnect are rejected whole with `AccessLost`. --- # Deploying on Vercel and Neon > A serverless deployment with no background process: connection strings, the release step, and what to watch. With HTTP sync (the client's default), clientdb runs entirely in Next.js route handlers, so a standard Vercel deployment with a Neon database is enough. No worker, no WebSocket server, nothing to configure in Neon. ## Connection strings | Variable | Neon URL | Used by | |---|---|---| | `DATABASE_URL` | pooled (`-pooler` host) | the engine in route handlers | | `DIRECT_URL` | direct | `engine.migrate()` and `prisma migrate deploy` (Prisma's `directUrl`) | Request-time locks are transaction-scoped, so the pooled URL (PgBouncer in transaction mode) works for every request. `engine.migrate()` takes a session advisory lock, so it uses `DIRECT_URL`, and refuses a pooled URL. The engine reads both variables itself: ```ts title="src/sync/engine.ts" import { createEngine } from "@clientdb/server"; import { permissions } from "./permissions"; export const engine = createEngine({ permissions, retention: { log: "30d" }, // without it the sync log grows forever }); ``` On Vercel the engine keeps its pool small (5 connections), since each serverless instance has its own. ## The route handler ```ts title="src/app/api/sync/[...path]/route.ts" import { clientdbHandler } from "@clientdb/server/next"; import { getSession } from "@/lib/auth"; // your auth library import { engine } from "@/sync/engine"; export const { GET, POST } = clientdbHandler(engine, { session: async (request) => { const session = await getSession(request); if (!session) { return null; } return { viewer: session.userId }; }, }); ``` No `runtime` or `dynamic` exports: route handlers run on Node.js by default (`pg` needs TCP), and Next 16 rejects both when `cacheComponents` is on. Don't put an edge runtime on a parent layout. ## The release step Run migrations before the new build starts serving: ```json title="package.json" { "scripts": { "vercel-build": "prisma migrate deploy && clientdb migrate src/sync/engine.ts && next build" } } ``` `clientdb migrate` imports your engine module, runs `engine.migrate()` on `DIRECT_URL`, prints what it did (for example `clientdb: migrated (applied nothing · rerouted todo · reconciled 3 todo)`), prunes what `retention` no longer keeps, and closes the connection. `clientdb migrate src/sync/engine.ts --dry-run` prints what it would do without changing anything. `prisma migrate deploy` also installs clientdb's [change triggers](/docs/guides/untracked-rows), since they ship as a Prisma migration (`npx clientdb-prisma triggers src/sync/schema.ts`). `migrate()` adopts and reconciles rows written outside clientdb, re-routes models whose shape or rules changed, and is safe to run on every deploy. ## Preview branches Each Neon branch has its own outbox and log, so preview deployments are isolated. Clients built for another schema get `SchemaOutdated` and reload, so a preview and production never mix state. ## What to watch - **Throughput**: inline sequencing reached 1,184 tx/s across 8 instances in the benchmark. If you outgrow it, run a WebSocket server with `engine.start()` elsewhere; route handlers keep working against the same log. - **Log growth**: `retention: { log: "30d" }` keeps 30 days of the sync log; every deploy prunes the rest (with no long-running process, nothing prunes hourly). A client that last synced before the oldest kept entry loads afresh and keeps its unsent changes. `engine.prune()` from a cron job prunes between deploys. - **Scale-to-zero**: fine. Nothing holds a slot or a long-lived session. --- # Security checklist > What clientdb protects on its own, and the settings and habits a production app needs on top: sessions and tokens, cookies and other sites, rules, limits and devices. clientdb decides what each viewer receives and may write from your rules, and refuses everything else. A few things are yours to get right. The examples use Framecast, a video-hosting app with teams, subscriptions and license keys. ## Who the viewer is The `session` callback is the only place the server learns who is signed in. Everything else trusts what it returns. - **Verify tokens with an audience.** `verifyJwt({ jwks, audience })` only accepts tokens issued for your app. Without `audience`, a token your auth provider issued for another of your apps signs that user in here too. Set `issuer` as well when your provider documents one. - **Use long, random secrets.** `tokens.secret` and `verifyJwt({ secret })` need at least 32 characters (`openssl rand -base64 32`). Anyone who learns the secret can mint a session for any user, so keep it in an environment variable, never in client code. - **Keep tokens short-lived.** Sync tokens last `ttlSeconds` (300 by default). Their claims and read-only flag hold until they expire, and a live socket checks its session again at that interval. When you revoke access, clients notice within one interval. - **Signed-out visitors** get a session only with `anonymous: true`, and then see only rows whose rule includes `$.public`, and can't write. ## Cookies and other sites A browser attaches your app's cookies to requests that other sites make. clientdb guards against the two ways that could matter: - `POST` bodies must be `Content-Type: application/json`, and other bodies get 415. A form on another site can't send JSON without a CORS preflight, so it can't push writes as the viewer. - A WebSocket opened by a page on another origin is refused (403) when it was authenticated by cookies, unless `cors` allows that origin. With a sync token in `?token=` it is accepted, because another site can't get the viewer's token. On your side: - Set session cookies `SameSite=Lax` (or `Strict`), `Secure` and `HttpOnly`. - List only your own origins in `cors`. `credentials: true` needs explicit origins; a function origin that returns true for anything has the same effect as `"*"`. ## Tokens in URLs Browsers can't set headers on WebSockets, so the browser client sends its token as `?token=` on the `/live` socket. The server reads `?token=` on WebSocket upgrades only, and the Swift client sends a header there too. URLs end up in access logs: - give the socket short-lived [sync tokens](/docs/transports/websocket#live-updates-on-another-host) rather than your auth provider's long-lived ones, so a logged token expires within minutes; - keep query strings of the `/live` path out of your proxy's logs. ## Rules and fields - A Framecast license's `key` belongs to its customer and to billing staff. Mark it `.restricted()` with a field rule: other team members still get the license, without the key, and they can't change the key or even name it in an update. With Prisma, `omit` keeps a column on the server altogether. - Models that clients never need, such as an audit log, are `serverOnly`: rules can read them, clients never receive them. - The server checks every written value against its field: type, enum values and nullability. A `validate` callback is for business rules, like "seats must be positive". - Archives are stamped with the server's time and the signed-in user, so archiving a row can't make retention delete it early. - The compiler refuses rules it can't route exactly; read the message rather than reshaping the rule until it compiles. ## The database - Run the engine as a role that owns clientdb's tables and the tables it syncs, not as a superuser. Superusers bypass [row-level security](/docs/server/postgres#row-level-security). - When a database constraint refuses a write, clients get `Conflict` or `Validation` with a plain message; the details are logged on the server. ## Limits clientdb doesn't rate-limit. Put limits in your proxy or platform, per IP and per signed-in user, on: - `POST …/push` and the WebSocket's transactions (writes); - `POST …/query` (server queries; `maxLimit` in the query rules caps the page size); - `GET …/token` and new WebSocket connections. Lower `bodyLimit` (16 MiB by default) to what your largest transaction needs. ## Devices - Local data isn't encrypted: IndexedDB in browsers, SQLite in the Swift client, protected by the operating system. Call `await db.$clear()` on sign-out so the next person on a shared computer doesn't inherit the data. - Any script running on your pages can read what the viewer reads, local data included. A Content Security Policy that blocks inline and third-party scripts limits what an injected script can do. --- # Testing > Test client code against an in-memory server with createTestClient, and permissions end to end with testEngine on a real Postgres. The examples test the todo app from the [quick start](/docs/quick-start), with [Vitest](https://vitest.dev). ## Client code: `createTestClient` `createTestClient` from `@clientdb/client/testing` gives you a real database client wired to an in-memory server: it applies transactions in arrival order, assigns revisions, cascades deletes along `onDelete: "cascade"` relations and broadcasts full rows to every connected client, with no permissions. The client starts with the seeded rows. ```ts title="test/todos.test.ts" import { createTestClient } from "@clientdb/client/testing"; import { expect, test } from "vitest"; import { schema } from "../src/sync/schema"; test("renaming a todo", async () => { const { db } = createTestClient(schema, { seed: { user: [{ id: "alice", name: "Alice", email: "alice@example.com" }], project: [{ id: "launch", name: "Launch" }], }, viewer: { model: "user", id: "alice" }, }); const todo = db.todo.create({ projectId: "launch", authorId: db.$session.viewerId!, title: "New" }); await todo.update({ title: "Renamed" }).confirmed; expect(db.todo.get(todo.id)?.title).toBe("Renamed"); }); ``` Options: - `viewer`: the signed-in viewer, as a server would report it, for `db.$session` and `db.$viewer`. `null` is an anonymous, read-only session. - `latencyMs`: a simulated network delay each way (demos). - `online: false` and `setOnline(next)`: offline periods; writes and server packets wait until the client is back online. - `server`: share one server between clients, e.g. two devices of the same user. - `mode: "manual"`: hold server packets until `server.deliver()`, to test optimistic state and rebase. - Every option of `createDatabaseClient` except the transport, such as `readOnly` or `models`. The server (`LoopbackServer`) can also refuse writes, to test rollbacks and `onTransactionError`: `new LoopbackServer(schema, { validate: (transaction, server) => { … } })`, passed as `server`. `server.serverWrite(operation)` simulates someone else's write. ## Permissions and sync: `testEngine` `testEngine` from `@clientdb/server/testing` runs a real engine on a real Postgres database, with no HTTP in between, to test what each user receives. It migrates and starts the engine and gives the test a tenant of its own, so tests can share one database. Its writes and `connect()` resolve once connected clients received the result, so tests never wait by hand. ```ts title="test/permissions.test.ts" import { testEngine } from "@clientdb/server/testing"; import { expect, test } from "vitest"; import { permissions } from "../src/sync/permissions"; test("admins see private todos", async () => { const testing = await testEngine({ permissions, database: process.env.TEST_DATABASE_URL! }); // typed writes without permission checks await testing.system.user.create({ id: "alice", name: "Alice", email: "alice@example.com" }); await testing.system.user.create({ id: "bob", name: "Bob", email: "bob@example.com" }); await testing.system.project.create({ id: "launch", name: "Launch" }); await testing.system.member.create({ id: "alice-launch", projectId: "launch", userId: "alice", role: "admin" }); await testing.system.member.create({ id: "bob-launch", projectId: "launch", userId: "bob", role: "member" }); await testing.system.todo.create({ projectId: "launch", authorId: "alice", title: "Shared" }); await testing.system.todo.create({ projectId: "launch", authorId: "alice", title: "Alice's notes", isPrivate: true }); const bob = await testing.connect("bob"); expect(bob.db.todo.all.map((todo) => todo.title)).toEqual(["Shared"]); await testing.system.member.update("bob-launch", { role: "admin" }); expect(bob.db.todo.count).toBe(2); // the private todo moved in bob.disconnect(); // goes offline, keeps local state await bob.reconnect(); // catches up from the last sync id await testing.close(); }); ``` `system` writes only the schema's fields, so a column `omit`ted from it (here `passwordHash`) needs a default in `schema.prisma`, or the row must be created with Prisma. The session can carry everything a real `session()` callback returns: - `testing.connect("bob", { readOnly: true })`: a read-only session; its writes are refused with `ReadOnly`. - `testing.connect("bob", { claims: [$staff()] })`: a session with [claims](/docs/guides/permission-recipes#staff-and-other-facts-about-the-session). - `await bob.setSession({ claims: [] })`: changes the claims or the read-only flag of a connected client, as a live server does when it checks the session again. Rows the session can no longer read leave `bob.db`. - `testing.connect(null)`: an anonymous visitor. `connectClient(engine, { viewer, tenant, claims, readOnly, load, eviction })` from `@clientdb/server/testing` (also exported by `@clientdb/server`) is the lower-level piece `testEngine` uses: a client on an engine you set up yourself. `load: "lazy"` and `eviction` test a client that loads every model when read, as an admin panel would. ## Checking rules without a database `compileAccess(permissions).explain()` prints the compiled plan; a rule that can't be routed throws `AccessCompileError` when the engine or plan is created, so a unit test that just builds the plan catches it in CI. ```ts title="test/rules.test.ts" import { compileAccess } from "@clientdb/server"; import { expect, test } from "vitest"; import { permissions } from "../src/sync/permissions"; test("permissions compile", () => { expect(() => { return compileAccess(permissions); }).not.toThrow(); }); ``` --- # Swift client > A native client for iOS 17 and macOS 14+: SwiftPM codegen from your schema, @Observable models, live queries, SQLite storage and SwiftUI helpers. The Swift client syncs with the same server as your web app. Each device keeps its own copy in SQLite, so the app opens instantly, works offline, and shows a change from another device as soon as it's saved. Its core is a Swift port of the same replica state machine and passes every conformance vector in `spec/vectors/`. Swift 6; Linux builds and tests everything except the SwiftUI helpers. The examples use the todo app from the [quick start](/docs/quick-start). | Module | What | |---|---| | `ClientDB` | The app-facing database: typed entities, live queries, writes, undo, sync over HTTP and WebSocket. Observation-based. | | `ClientDBSQLite` | SQLite storage on GRDB: rows, sync state, and the queue of unsent changes | | `ClientDBPlugin` | SwiftPM build-tool plugin that generates the model classes from `clientdb.schema.json` | | `ClientDBCore` | The platform-neutral replica; comes with `ClientDB` | ## Setup 1. Export the schema from the server project (the Prisma generator writes it too): ```ts title="scripts/export-schema.ts" import { writeFileSync } from "node:fs"; import { exportSchema } from "@clientdb/schema"; import { schema } from "../src/sync/schema"; writeFileSync("clientdb.schema.json", JSON.stringify(exportSchema(schema))); ``` 2. Put `clientdb.schema.json` in your app target's sources and add the plugin: ```swift title="Package.swift" .target( name: "App", dependencies: [ .product(name: "ClientDB", package: "clientdb"), .product(name: "ClientDBSQLite", package: "clientdb"), ], plugins: [.plugin(name: "ClientDBPlugin", package: "clientdb")] ) ``` In an Xcode project, add the package and enable the plugin under the target's Build Phases → Run Build Tool Plug-ins. Headless CI builds pass `-skipPackagePluginValidation` to `xcodebuild`. Every build regenerates the models: one class per model with typed fields, nested enums, forward relations (`todo.project`), inverse relations as live queries (`project.todos`), and `Insert` / `Changes` structs. Never edit them; add app logic in extensions: ```swift extension Todo { func rename(_ title: String) throws { try update { $0.title = title.trimmingCharacters(in: .whitespaces) } } } ``` ## Open the database ```swift let db = try await ClientDB.open( schema: .generated, storage: SQLiteStorage(applicationSupport: "clientdb.sqlite"), sync: SyncOptions( url: URL(string: "https://app.example.com/api/sync")!, realtime: true, token: { await Session.current.token() } // your auth ) ) try await db.ready() // eager models usable, from SQLite or the network ``` The server decides who the user is from the token (its `session()` callback); the client never sends a user id of its own. Stored data belongs to the signed-in user: when the server reports a different one, the device copy is deleted and loaded again. `await db.clear()` does the same on sign-out. `ClientDB.open` also takes `load: .lazy` (every model loads when read, for admin tools), `eviction: .maxRows(5_000)` (see [Lazy models](#lazy-models-load-when-read)) and `readOnly: true`. ## Reads Entities are `Observable` per field; queries are maintained incrementally. ```swift let open = db.todos.where(\.projectId == projectID, \.done == false).sorted(by: \.updatedAt, .descending).limit(50) open.rows // [Todo] open.count // ignoring the limit project.todos // the same kind of query, shared per project ``` ## Lazy models load when read Models are `eager` (loaded at sign-in) or `lazy` (the default), as on the web. A lazy model fetches its rows by the key a read uses, such as `todo.comments`, or whole on other reads. Reads in the same main-actor turn, such as one SwiftUI render of a list whose rows each read `todo.comments.count`, share one request, and each set of rows is fetched once: ```swift todo.comments.count // 0 at first; updates when the comments arrive todo.comments.status // .partial, .loading, .complete or .failed(reason) try await todo.comments.preload() // optional: fetch early, e.g. before navigating to the todo ``` A failed fetch isn't retried on every read; `preload()` tries again. With `eviction: .maxRows(n)`, the loads used longest ago (a todo's comments, a server query's pages) are dropped whole once the device holds more rows; a query over them reads `.partial` and loads again when read. What the app still holds stays: a `LiveQuery`, a `ServerQuery` or an entity keeps the loads it reads. Eager models and rows with unsent writes or drafts always stay. ## Server queries To search rows that aren't on the device, ask the server. The model's `query` rules on the server say which fields and operators are allowed: ```swift let results = db.comments.query( where: .contains(\.body, "launch", caseInsensitive: true), sortedBy: \.createdAt, .descending, limit: 20 ) results.rows // the rows so far results.status // .loading, then .complete results.hasMore try await results.loadMore() ``` ## Writes Writes are visible at once and sent in the background. ```swift let todo = try db.todos.create(.init(title: "New", projectId: projectID, authorId: db.session.viewerId!)) try todo.update { $0.title = "Renamed" } try await todo.delete().confirmed() // throws the TransactionRejection if the server refuses try db.transaction { tx in let second = try tx.create(Todo.self, .init(title: "Second", projectId: projectID, authorId: db.session.viewerId!)) try tx.update(second) { $0.done = true } } try db.undo() // reports fields someone else changed meanwhile ``` `Insert` has every field the client may write, including `authorId`: pass `db.session.viewerId` yourself. The server's rules check the value (`enforce: ($) => ({ authorId: $.viewer.id })`) and reject a write that names someone else; they never fill it in. Generated fields aren't in `Insert` and are read-only. ## Server logic Logic that runs on your server (an API call that writes with Prisma) goes through `db.action`, which calls it and then waits for a sync, so its rows are on the device when it returns. `optimistic` shows the result before the server answers, and is dropped once the server's own write has synced: ```swift try await db.action(optimistic: { db in try db.todos[todoID]!.update { $0.done = true } }) { try await api.completeTodo(todoID) } ``` ## Forms: drafts ```swift try todo.edit { $0.title = "Typing…" } // unsaved edit on top of the row try todo.save() // or todo.revert() ``` ## Session and restricted fields `db.session` is what the server verified: `viewer`, `viewerId`, `claims` (`db.session.hasClaim("staff")`) and `readOnly`. `db.viewer(User.self)` is the viewer's row. Writes in a read-only session, or on a database opened with `readOnly: true`, throw `CoreError` `.readOnly`. A [restricted field](/docs/guides/permission-recipes#fields-only-some-users-may-see) the viewer may not read is `nil`; `user.isHidden(\.email)` tells it apart from a field that is empty. ## SwiftUI Put the database in the environment and use `@Live`: ```swift ContentView() .environment(db) .syncsOnForeground(db) struct TodosView: View { @Live(.where(\.done == false).sorted(by: \.createdAt)) var todos: [Todo] var body: some View { List(todos) { todo in Text(todo.title) } } } ``` ## Status and concurrency `db.syncStatus` is `idle`, `bootstrapping`, `syncing`, `online`, `offline(reason)` (retried with backoff), `outdated(reason)` (the server runs another protocol or schema version; update the app) or `closed`. `try await db.sync()` returns once the device has everything the server had when it was called. The database and entities live on the main actor; network IO and JSON decoding run off it. ## Tests ```bash swift test # vectors, codegen golden files, client, storage, sync (fake server) CLIENTDB_TEST_PG=postgres://… swift/E2E/run.sh # against the real server CLIENTDB_UPDATE_GOLDEN=1 swift test --filter Golden # after a generator change ``` On Linux, `URLSession` WebSockets need a libcurl built with WebSocket support (Ubuntu's isn't); without one, realtime falls back to polling. CI builds one so the end-to-end job covers the live path. --- # Schema in TypeScript > Define models, fields and relations once; the schema types every read, write and permission rule, on the server and in the browser. The schema is one value that the server and every client import. It says which models exist, their fields, how they relate, and when their rows reach a device. Everything else is typed from it: reads, writes, [permission rules](/docs/server/permissions), and the Swift client's model classes. Without Prisma, you write it in TypeScript, as on this page. With Prisma, [`fromPrisma`](/docs/schema/prisma) builds the same value from `schema.prisma`. The example is the todo app from the [quick start](/docs/quick-start) (users, projects, members, todos and comments), with a few additions so every option appears once. ## A schema file ```ts title="src/sync/schema.ts" import { createSchema, model, t, type InferSchema } from "@clientdb/schema"; const user = model( { name: t.string(), email: t.string().unique(), avatarUrl: t.string().nullable(), }, { load: "eager" }, ); const project = model( { name: t.string(), budget: t.decimal().nullable(), // exact: "1200.50" /** Lets people join the project; only admins receive it (see its field rule). */ inviteCode: t.string().unique().restricted(), }, { load: "eager", archivable: true }, ); const member = model( { project: t.belongsTo("project", { inverse: "members", onDelete: "cascade" }), user: t.belongsTo("user", { inverse: "memberships" }), role: t.enum(["member", "admin"]).default("member"), }, { load: "eager", indexes: [["projectId", "role"]] }, ); const todo = model( { id: t.uuid({ prefix: "todo" }).id(), // todo_01932c… number: t.number().generated(), // #42, filled in by Postgres project: t.belongsTo("project", { inverse: "todos", onDelete: "cascade" }), author: t.belongsTo("user", { inverse: "todos" }), assignee: t.belongsTo("user", { inverse: "assignedTodos" }).nullable(), title: t.string(), done: t.boolean().default(false), isPrivate: t.boolean().default(false), createdAt: t.timestamp().defaultNow(), updatedAt: t.timestamp().updatedAt(), }, { load: "eager" }, ); // lazy, the default: a todo's comments load the first time `todo.comments` is read const comment = model({ todo: t.belongsTo("todo", { inverse: "comments", onDelete: "cascade" }), author: t.belongsTo("user", { inverse: "comments" }), body: t.string(), createdAt: t.timestamp().defaultNow(), }); // stays on the server: rules and your backend can read it, clients never see it const auditEntry = model( { actor: t.belongsTo("user", { inverse: "auditEntries" }), action: t.string(), createdAt: t.timestamp().defaultNow(), }, { serverOnly: true }, ); const builtSchema = createSchema({ user, project, member, todo, comment, auditEntry }); /** A named type, so editor hovers show `Schema` instead of the whole structure. */ export interface Schema extends InferSchema {} export const schema: Schema = builtSchema; ``` - `model(fields, options)` describes one model. It gets its name from its key in `createSchema`: `member`, `auditEntry`. - Relations name their target model as a string, so models can point at each other in any order, and across files. - Every model has an `id`, a UUIDv7 generated on the device that creates the row. Declare it only to change it (here, a `todo_` prefix). - The `InferSchema` interface is optional; it only keeps type hovers short. `export const schema = createSchema({ … })` works the same. Mistakes that involve one model are type errors on the offending property, and those that involve two (an unknown target, an inverse name that collides with a field) on the property in `createSchema`. The same checks run again when the schema is built, for plain JavaScript. ## Fields | Field | Type on the client | Notes | |---|---|---| | `t.string()` | `string` | | | `t.number()` | `number` | | | `t.boolean()` | `boolean` | | | `t.timestamp()` | `number` | a time, as milliseconds since 1970 (not a `Date`); `new Date(todo.createdAt)` to format it | | `t.enum(["member", "admin"])` | `"member" \| "admin"` | | | `t.json()` | `T` | any JSON value; `T` is only a type, nothing checks it at runtime | | `t.uuid()` | `string` | a UUID-valued column; `t.uuid({ prefix: "todo" })` generates `todo_` values | | `t.decimal()` | `string` | exact decimals (Postgres `numeric`), sent as strings such as `"1200.50"`, never as floats | Every field takes these options: | Option | Meaning | |---|---| | `.nullable()` | the value may be `null`; nullable fields are optional on create | | `.default(value)` | used when a create leaves the field out. `.default(() => value)` computes it on the device, in TypeScript only (the Swift client needs a plain value) | | `.defaultNow()` | on timestamps: the current time on create | | `.defaultUuid()` | on uuids: a new UUIDv7 on create, with the field's prefix | | `.updatedAt()` | on timestamps: set on create and on every update, at once on the device and again by the server, like Prisma's `@updatedAt` | | `.unique()` | the field identifies one row: a unique index, and a lazy read by it (`db.user.where({ email })`) loads that row | | `.indexed()` | an index for reads that filter by it; foreign keys and unique fields are indexed already | | `.generated()` | Postgres fills it in (an identity column on engine-owned tables, a sequence or trigger on yours). Clients read it but never send it: it's left out of the create and update types, and is `null` on the device until the server confirms the create | | `.restricted()` | only viewers allowed by the field's own [read rule](/docs/server/permissions#restricted-fields) receive its value; for everyone else it is `undefined`, so its type on the client is `T \| undefined` | | `.id()` | on the field named `id`: this field is the id. `t.uuid({ prefix: "pay" }).id()` makes ids such as `pay_01932c…` on every client, matching ids your backend creates. A prefix is letters and digits, starting with a letter | Only numbers can be `.generated()` on engine-owned tables. On Prisma's tables, any column with `@default(autoincrement())` or `@default(dbgenerated(…))` is generated. ## Relations: `t.belongsTo` A relation is declared once, on the model that holds the key: ```ts // in `todo`: author: t.belongsTo("user", { inverse: "todos" }), ``` That one line adds three things: - the key column `authorId` (a `string`), which you pass on create: `db.todo.create({ authorId: viewerId, … })`; - the relation `todo.author`, the user row; - the collection `user.todos`, every todo whose `authorId` is that user. The name comes from `inverse`. | Option | Meaning | |---|---| | `inverse` | required: the name of the collection on the target (`user.todos`) | | `.nullable()` | the relation is optional: the key column may be `null` | | `foreignKey` | the key column's name, when it isn't the relation name plus `Id`: `t.belongsTo("user", { inverse: "todos", foreignKey: "createdBy" })` | | `onDelete` | what deleting the target does to this row: `"setNull"` (the default for nullable relations), `"restrict"` (the default for required ones: the delete is refused while rows point at it) or `"cascade"`; see below | | `eager: true` | the rows come along whenever their target arrives on a device; see below | ### Cascading relations `onDelete: "cascade"` says the row lives and dies with its target. A comment without its todo means nothing, so `comment.todo` cascades: - Deleting the todo deletes its comments, on the device at once and on the server; undo brings the whole subtree back. - A comment counts as archived while its todo is: archiving the todo's project hides the project's todos and their comments too. A model may cascade from several relations. A row then goes when any of its targets is deleted, and counts as archived while any of them is archived. Cascading says nothing about who may read the row. Give the comment a read rule like any other model; `$.canRead(comment.todo)` makes it readable whenever its todo is (see [Permissions](/docs/server/permissions#reading-like-the-parent)). ### Eager relations `eager: true` means: whenever a target row arrives on a device, the rows that point at it through this relation come with it, however the target arrived. If comments should travel with their todo instead of loading on first read, mark the relation: ```ts // in `comment`: todo: t.belongsTo("todo", { inverse: "comments", onDelete: "cascade", eager: true }), ``` The cascade has fixed limits, so loading one row can't pull in a whole database: - It only goes down, from a target to the rows marked `eager: true` that point at it, and on from those. - The rows those point at (a comment's author) 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. ## Load modes `load` decides when a model's rows reach a device: | `load` | Rows arrive | |---|---| | `"lazy"` (the default) | when something reads them: a relation (`todo.comments`), a unique field (`where({ email })`), an id (`get(id)`), or the whole model (`db.comment.all`) | | `"eager"` | when the client starts: every row of the model the user may read | A lazy read returns what's on the device at once, and its `status` says whether more is on the way (see [Reading data](/docs/client/queries#lazy-models-load-when-read)). Use eager for models that stay small per user, such as their projects and teammates. A lazy model loads by `id`, by a unique field or by a foreign key; a read by any other field loads the whole model. On your own tables, give every foreign key an index, since Postgres doesn't add one: engine-owned tables have them already. If one user may read 100,000 rows of an eager model, all of them load at startup, so the engine warns when a first load sends more than 20,000 rows (`createEngine({ bootstrapRowWarning })`). ## Other model options | Option | Meaning | |---|---| | `archivable: true` | adds `archivedAt` and `archivedBy`, and `project.archive()` / `project.unarchive()`: an archived row is hidden on every device, with the rows that cascade from it, and kept in the database. See [Archive and delete](/docs/server/archive-delete) | | `serverOnly: true` | the model stays on the server. Rules can read it (a membership table that decides who sees what), your backend can write it, and clients get no API for it or its relations. It needs no rules | | `indexes: [["projectId", "role"]]` | extra indexes on engine-owned tables, for reads that filter on several fields | ## The viewer model Signed-in users are rows of one model: `user`, when the schema has one. Name another with `createSchema(models, { viewer: "account" })`. It types `db.$viewer` on the client and `$.viewer` in [rules](/docs/server/permissions); your session callback returns the id of the viewer's row. ## Types ```ts title="src/sync/types.ts" import type { EntitiesOf } from "@clientdb/client"; import type { ClientRow, Insert, Row, Update } from "@clientdb/schema"; import type { Schema } from "./schema"; /** Entities by PascalCase model name, with their fields, relations and write methods: `DB["Todo"]`. */ export type DB = EntitiesOf; export type TodoRow = Row; // every field, as stored export type ProjectOnClient = ClientRow; // restricted fields as `T | undefined` export type NewTodo = Insert; // fields with defaults, nullable and generated ones optional or absent export type TodoChanges = Update; // any subset of the writable fields ``` ## Exporting the schema for other clients The Swift client, and any other implementation of the [protocol](/docs/reference/protocol), reads the schema as JSON (`clientdb.schema.json`): ```ts title="scripts/export-schema.ts" import { writeFileSync } from "node:fs"; import { exportSchema } from "@clientdb/schema"; import { schema } from "../src/sync/schema"; writeFileSync("clientdb.schema.json", JSON.stringify(exportSchema(schema), null, 2)); ``` Run it whenever the schema changes, and commit the file with the app that reads it. See [Swift](/docs/swift). --- # Prisma as the source of truth > Build a fully typed clientdb schema from schema.prisma with fromPrisma, run on Prisma's tables, and sync the writes your app makes with Prisma Client. If your app already uses Prisma, `schema.prisma` stays the source of truth. Models, fields, nullability, defaults, ids and relations come from it, and the tables stay Prisma's: clientdb never runs DDL on them. You only add what Prisma can't say, such as which models load at startup. The examples use the todo app from the [quick start](/docs/quick-start): users, projects, members and todos, with comments on todos. ## The generator ```prisma title="prisma/schema.prisma" generator clientdb { provider = "clientdb-prisma" output = "../src/generated/clientdb" } ``` `prisma generate` now also writes `src/generated/clientdb/index.ts`: your Prisma models as plain `as const` data. It has literal types, so `fromPrisma` can type every model and field from it, and it is safe to import in the browser. Nothing else is generated: entity classes are built at runtime. The generator fails with a clear message until clientdb's own tables are in `schema.prisma` (see [below](#clientdbs-tables-as-prisma-models)). ## `fromPrisma(prismaModels, options)` ```ts title="src/sync/schema.ts" import { fromPrisma } from "@clientdb/prisma"; import { prismaModels } from "../generated/clientdb"; export const schema = fromPrisma(prismaModels, { omit: { User: ["passwordHash"] }, // never leaves the server models: { User: { load: "eager" }, Project: { load: "eager", archivable: true }, Member: { load: "eager" }, Todo: { load: "eager" }, Comment: { relations: { todo: { eager: true } } }, // comments arrive with their todo }, }); export type Schema = typeof schema; ``` `prismaModels` is the generator's output, and this file is the only place that uses it. The schema also remembers which table and columns each model uses, so the rest of your code, server and client, only passes `schema` around. Everything is typed against your Prisma models: a misspelled model (in `models`, `omit`, `notSecret` or a model list), field or relation is a type error on that key, and a runtime error that names it. To keep options in their own constant, check it with `satisfies FromPrismaOptions`. ### Top-level options | Option | Meaning | |---|---| | `models` | per-model options, keyed by Prisma model name (below). A model you don't list syncs lazily, with no extra options | | `omit` | columns that never leave the server, per model. When clients create a row, omitted columns take their database defaults; a required omitted column without a default (`User.passwordHash`) means clients can read the model but not create it. A `/// @clientdb.omit` comment above a field in `schema.prisma` does the same | | `notSecret` | columns whose names look secret but are fine to send (see [secret-looking columns](#secret-looking-columns)) | | `serverOnly` | models that stay on the server: rules can read them, your backend writes them, clients get no API for them. They need no rules | | `exclude` | models left out entirely. Relations into them are dropped, and their foreign keys stay plain fields | | `include` | auth models to sync anyway. `Session`, `Account`, `Verification` and `VerificationToken` are excluded by default | | `viewer` | the model whose rows are the signed-in users (default `User`); it types `db.$viewer` and `$.viewer` | ### Per-model options: `models` | Option | Meaning | |---|---| | `load: "eager"` | every row of the model the user may read arrives when the client starts. Default `"lazy"`: rows load when something reads them. See [load modes](/docs/schema#load-modes) | | `relations` | options of the relations that hold a foreign key, by relation field name. The one option is `eager: true`, as on [`t.belongsTo`](/docs/schema#eager-relations); `onDelete` comes from `schema.prisma` | | `restricted: ["inviteCode"]` | fields only some viewers receive, each with its own [field read rule](/docs/server/permissions#restricted-fields) | | `archivable: true` | enables `archive()` and `unarchive()`. Needs nullable `archivedAt DateTime?` and `archivedBy String?` columns | | `id: { prefix: "todo" }` | ids created on devices are `todo_`. Needs a single `String` id column (not `@db.Uuid`) | The checks behind these options: - `relations` only takes the side that holds the key: `Todo.project`, not `Project.todos`. Putting options on the list side is a type error that names the right field. - `onDelete` is never an option: it is the relation's referential action in `schema.prisma`, so deleting a todo with Prisma Client and with clientdb removes the same rows. `onDelete: Cascade` on `Comment.todo` deletes a todo's comments on devices too, restores them on undo, and counts them as archived while their todo is, like [`onDelete: "cascade"`](/docs/schema#cascading-relations) in a TypeScript schema. - `archivable: true` on a model without both archive columns is a type error that names the missing ones, for example `archivable needs archivedBy String? in schema.prisma`. An archivable model keeps its archive state in its own columns: ```prisma title="prisma/schema.prisma" model Project { id String @id @default(uuid(7)) name String archivedAt DateTime? archivedBy String? members Member[] todos Todo[] } ``` `project.archive()` on a device sets both, and so does any write of your own (`prisma.project.update({ data: { archivedAt: new Date() } })`). Either way the project is hidden on every device. With `retention.archived`, the engine deletes projects archived longer than that; see [Archive and delete](/docs/server/archive-delete). ### Secret-looking columns A column whose name contains `token`, `secret`, `hash`, `password`, `salt` or `key` must be listed in `omit`, in `models..restricted`, or in `notSecret`; otherwise `fromPrisma` is a type error and a runtime error that name it. So an `apiToken` column added in a later migration can't reach browsers by accident: ```ts notSecret: { Attachment: ["storageKey"] }, // an object storage path, fine to send ``` ## How Prisma maps | Prisma | clientdb | |---|---| | model `TeamMember` | model `teamMember` (camelCase, like Prisma Client) | | `String`, `String @db.Uuid` | `t.string()`, `t.uuid()` | | `Int`, `Float`, `BigInt` | `t.number()` (BigInt is exact up to 2^53) | | `Decimal` | `t.decimal()`: exact, sent and typed as a string such as `"49.00"` | | `DateTime` | `t.timestamp()`: milliseconds since 1970. A `timestamp` column without time zone is read as UTC, as Prisma writes it | | `Boolean`, `Json` | `t.boolean()`, `t.json()` | | enums | `t.enum([…])` | | `String[]` and other lists | arrays (a `json` field) | | `?` | `.nullable()` | | `@unique` | `.unique()`: a lazy read by it (`where({ email })`) loads that row | | `@default(now())`, literals | the same default, applied on the device | | `@default(uuid())`, `uuid(7)`, `cuid()`, `ulid()`, `nanoid()` | a UUIDv7 generated on the device | | `@default(autoincrement())`, `sequence()`, `dbgenerated(…)` | `.generated()`: Postgres fills it in, clients never send it | | `@updatedAt` | `.updatedAt()`: set on create and on every update | | `@id` on `id` | the model's `id` | | `@@id([a, b])`, or `@id` on another field | a derived `id`: the key fields joined with `\|`. Key fields can't be updated | | a relation with `fields: [projectId]` | a `belongsTo` relation; the back-relation (`Project.todos`) is its inverse | | `onDelete: Cascade`, `SetNull`, other (`Restrict`, `NoAction`, `SetDefault`) | `"cascade"`, `"setNull"`, `"restrict"`; without one, Prisma's defaults (`SetNull` for optional relations, `Restrict` for required ones) | Give every foreign key of a lazy model an index (`@@index([todoId])`): lazy reads load by foreign key, and Postgres doesn't index them on its own. ## clientdb's tables as Prisma models clientdb keeps its bookkeeping (the sync log, row metadata, the triggers' queue) in a few tables. Add them to `schema.prisma`, so Prisma creates and migrates every table: ```bash npx clientdb-prisma models >> prisma/schema.prisma # or a separate file in a multi-file schema npx prisma migrate dev --name clientdb ``` The engine runs no DDL, and `prisma migrate diff` reports no drift after it has run. **When you upgrade clientdb**, replace that block with the current `npx clientdb-prisma models` and run `prisma migrate dev`: newer versions add columns (such as `clientdb_row.field_readers` and `clientdb_log.created_at`). Until then, `clientdb migrate` stops with an error that names the missing column. ## Writes your app makes with Prisma The engine writes clients' changes straight into your tables. Writes your own code makes, with Prisma Client, raw SQL, scripts or other services, are picked up by Postgres triggers, which ship as a Prisma migration: ```bash npx clientdb-prisma triggers src/sync/schema.ts > prisma/migrations/20261202_clientdb_triggers/migration.sql npx prisma migrate dev ``` `triggers ` imports your schema module (`--export name` when the schema isn't exported as `schema`) and prints the triggers for every model it maps, `serverOnly` ones included, since rules read them. It also drops the triggers of tables that no longer sync. Run it again, into a new migration, when you add or remove a model. Your write code then needs no clientdb calls: ```ts title="src/app/projects/actions.ts" "use server"; import { prisma } from "@/lib/prisma"; export async function promote(memberId: string) { await prisma.member.update({ where: { id: memberId }, data: { role: "admin" } }); // syncs on its own } ``` The triggers record each changed row in the same transaction as your write, and catch nested writes, `createMany` / `updateMany` / `deleteMany`, raw SQL and rows Postgres changed by cascade. See [Writes from your server](/docs/guides/untracked-rows) for the details, the safety net `engine.reconcile()`, and `engine.changed()` for apps that can't install triggers. ## Deploying Run `clientdb migrate` after Prisma's own migrations: ```bash npx prisma migrate deploy npx clientdb migrate src/sync/engine.ts ``` - The first run adopts every row that existed before clientdb (about 2 seconds for 20,000 rows). Later runs sync rows written outside clientdb that no trigger caught, such as seeds run before the triggers existed. - When a `prisma migrate` changed a model's fields, or your rules changed, it re-routes that model's rows to the right devices. - Until it has run for the current schema and rules, the sync routes answer `503 NotMigrated`. See [Migrations](/docs/server/migrations). ## Limits - One engine tenant on Prisma's tables: tenancy inside your app comes from your rules. - `fromPrisma` refuses, with an error that names the field: ids that aren't `String`, composite foreign keys, `@map` on enum values, `Bytes` and other unsupported types, and `@default` functions it doesn't know. Omit the field, or exclude the model. - `BigInt` values beyond 2^53 lose precision on clients. --- # The engine > createEngine ties your permissions and your database together: its options, hooks and retention, its lifecycle from install to prune, and writing from your server. The engine is clientdb's server side. It checks every write from a device against your rules and applies it, keeps the sync log, sends each device the rows it may read, and works out what to add or remove when someone's access changes. You create it once and hand it to a [route handler](/docs/transports/http) or a [Node server](/docs/transports/node). The examples use the todo app from the [quick start](/docs/quick-start). ```ts title="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 schema comes from `permissions`: it's the one you passed to `definePermissions(schema, …)`. - Creating the engine costs nothing: it opens its connection pool on first use (5 connections on serverless hosts such as Vercel), so a module-level engine is fine during `next build`. - Without `database`, it connects to `DATABASE_URL` and logs once that it did. - In development, one engine per database survives hot reloads of the route module, so edits don't leak connections. When the schema or rules change, the old engine is closed and replaced. - Rules are compiled when the engine is created; a rule the engine can't route to devices throws `AccessCompileError` right there. See [Groups and routing](/docs/server/groups#what-the-compiler-rejects). ## Where rows live - **Prisma's tables**, when the schema comes from [`fromPrisma`](/docs/schema/prisma): the schema carries the table and column mapping, and the engine reads and writes your tables. Its own bookkeeping lives in `clientdb_*` tables that you add to `schema.prisma`; your tables are never altered. - **Engine-owned tables** otherwise: one `m_` table per model, created by `engine.migrate()`. Schema changes then go through [migrations](/docs/server/migrations). ## Options | Option | Meaning | |---|---| | `permissions` | required: the rules from `definePermissions` | | `database` | a Postgres URL, or a `pg.Pool` you manage yourself (default: `DATABASE_URL`) | | `directUrl` | the direct, non-pooled connection `migrate()` needs for its lock (default: `DIRECT_URL`) | | `hooks` | `onWriteRejected` and `onAccessRemoved`, for logs and metrics ([below](#hooks)) | | `retention` | how long the sync log and archived rows are kept ([below](#retention)) | | `bootstrapRowWarning` | warn when one first load sends more rows than this (default 20,000; `false` turns it off) | | `cascadeRowLimit` | the most rows one load brings through [eager relations](/docs/schema#eager-relations) (default 5,000) | | `resyncInvalidateThreshold` | above this many rows, `engine.resync(model)` tells clients to reload the model instead of sending each row (default 10,000) | | `migrations` | versioned migrations for engine-owned tables, applied by `migrate()` | | `snapshotStore` | a cache for first loads, shared by everyone who reads the same rows: `MemorySnapshotStore`, `FsSnapshotStore` or your own | | `rowLevelSecurity` | adds Postgres row-level security per tenant on engine-owned tables, as defense in depth | ### Hooks Hooks receive who did what and the outcome, never row data, so they are safe to log: ```ts title="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 }) => { logger.info("access removed", { viewer: session.viewer, groups, reason }); }, }; ``` - `onWriteRejected` runs when the server refuses a transaction. `code` is the [rejection code](/docs/reference/errors#rejection-codes) (`Forbidden`, `Validation`, `ReadOnly`, …), and `failedBranches` lists the labels of the rule's `$.anyOf` branches, none of which held. - `onAccessRemoved` runs when a session loses [groups](/docs/server/groups), so rows leave its devices. `reason` is `"claim"` when your session callback stopped granting a claim, and `"rules"` when a write changed what the rules give the viewer. A hook that throws is logged and never breaks sync. ### Retention Without `retention`, the sync log, the ids of applied transactions and archived rows are kept forever. With it: - `log: "30d"` deletes sync-log entries older than 30 days (at least `"1h"`). A device last synced before the oldest kept entry loads afresh, and keeps its unsent changes. - `transactions: "180d"` deletes the ids of applied device transactions older than that (at least `log`; default the longer of `log` and `"90d"`). While an id is kept, a resend of its transaction is confirmed without applying it again. After that, a resend the server may have applied is refused with [`Stale`](/docs/server/conflicts#at-most-once) instead. - `archived: "90d"` deletes rows of [archivable](/docs/server/archive-delete) models archived more than 90 days ago, with the rows that cascade from them, and the deletes reach every device. A row that a `restrict` relation still points at stays. Periods are days (`"30d"`) or hours (`"12h"`). Pruning runs on every `clientdb migrate`, hourly in a process that called `engine.start()`, and whenever you call `engine.prune()`, for example from a cron job on a serverless deployment: ```ts title="src/app/api/cron/prune/route.ts" import { engine } from "@/sync/engine"; export async function GET() { const pruned = await engine.prune(); // { logEntries, transactions, archived: { project: 2 }, archivedKept: {} } return Response.json(pruned); } ``` ## Lifecycle | Call | What it does | |---|---| | `npx clientdb migrate src/sync/engine.ts` | the deploy step: runs `engine.migrate()`, then `engine.prune()` when the engine sets `retention`, prints what they did and closes the pool | | `npx clientdb migrate src/sync/engine.ts --dry-run` | prints what that would do, and changes nothing | | `engine.migrate()` | creates or checks clientdb's tables, applies pending migrations, adopts and reconciles rows written outside clientdb (Prisma), and re-routes models whose rules changed. It needs a direct connection: a pooler URL is refused | | `engine.migrationPlan()` | what `migrate()` and `prune()` would do, read without writing (what `--dry-run` prints) | | `engine.prune()` | applies `retention` now | | `engine.start()` / `engine.stop()` | the background sequencer, which live connections need (`createSyncServer` starts it for you) | | `engine.idle()` | resolves when every committed write has reached every connection (useful in tests) | | `engine.close()` | stops the engine and closes the pool it opened; `await using engine = createEngine(…)` does it for you | Until `migrate()` has run for the current schema and rules, the routes answer `503 NotMigrated` and log why. With the HTTP and Next.js handlers you don't call `start()`: each request does the sequencing it needs. See [Outbox and sequencer](/docs/server/outbox). ## Writing from the server clientdb doesn't run your business logic. Logic that must run on the server (charging a card, sending an email, checks across many rows) stays in your own server actions, tRPC procedures and API routes, which write to the database as they do today. The browser calls them through [`db.$action`](/docs/client/mutations#server-logic-with-action), which waits until the rows they wrote are on the device. **With Prisma**, write with Prisma Client. The [triggers](/docs/guides/untracked-rows) bring every write to the devices that may see it, with no clientdb calls: ```ts title="src/app/projects/actions.ts" "use server"; import { prisma } from "@/lib/prisma"; export async function clearDoneTodos(projectId: string) { await prisma.todo.deleteMany({ where: { projectId, done: true } }); // reaches every member's devices } ``` **Without Prisma**, or for jobs that should go through clientdb, use `systemWrite`. It applies operations without permission checks, in one transaction: ```ts title="scripts/seed.ts" import { engine } from "@/sync/engine"; const projectId = crypto.randomUUID(); await engine.systemWrite([ { type: "create", model: "project", id: projectId, data: { name: "Launch" } }, { type: "create", model: "todo", id: crypto.randomUUID(), data: { projectId, authorId: "user_1", title: "Write the announcement" } }, ]); ``` Operations are `create`, `update`, `delete`, `archive` and `unarchive`. On engine-owned tables with several tenants, pass `{ tenant }` as the second argument. Three more calls cover writes clientdb didn't see: | Call | When | |---|---| | `engine.reconcile()` | compares Prisma's tables with what clientdb last sent and syncs every difference. `migrate()` runs it; you can also run it from a cron job | | `engine.changed({ todo: [todoId] })` | apps that can't install the triggers: say which rows you wrote, inside your transaction for atomicity | | `engine.resync("todo")` | after a bulk change in SQL: sends the whole model again (`engine.resync()` for every model) | See [Writes from your server](/docs/guides/untracked-rows). ## Inspecting the compiled rules ```ts title="scripts/explain-rules.ts" import { compileAccess } from "@clientdb/server"; import { permissions } from "@/sync/permissions"; console.log(compileAccess(permissions).explain()); ``` This prints every group kind, how each model's rows are routed, and which rows decide who belongs to which group. See [Groups and routing](/docs/server/groups). ## Serving it - [HTTP and Next.js](/docs/transports/http): `clientdbHandler` or `createFetchHandler`. - [Node.js servers](/docs/transports/node) and [live updates](/docs/transports/websocket): `createSyncServer`. --- # HTTP: pull and push (no sockets) > Sync over plain HTTP: the Next.js route handler and its session callback, read-only routes, a fetch-standard handler for any runtime, the endpoints, and when the client syncs. By default, clientdb syncs over plain HTTP: no long-running process and no WebSocket. The device pulls on load, on focus, after writes and every 30 seconds while the tab is visible; a pull also carries the device's unsent writes, so one round trip sends and receives. The server works out the order of writes inside the requests themselves, so any number of serverless instances can run at once. ## Next.js App Router The examples use the todo app from the [quick start](/docs/quick-start). ```ts title="src/app/api/sync/[...path]/route.ts" import { clientdbHandler } from "@clientdb/server/next"; import { auth } from "@/lib/auth"; // e.g. Better Auth import { getStaffLogin } from "@/lib/staff"; import { $support } from "@/sync/claims"; import { engine } from "@/sync/engine"; export const { GET, POST } = clientdbHandler(engine, { session: async (request) => { const session = await auth.api.getSession({ headers: request.headers }); if (!session) { return null; // signed out: 401 } return { viewer: session.user.id, // the id of the signed-in user's `User` row claims: [$support(Boolean(await getStaffLogin(session.user.id)))], readOnly: session.user.suspendedAt !== null, // suspended users still see their todos, but can't change them }; }, }); ``` No route segment config is needed: route handlers run on Node.js by default (Postgres needs TCP), and a handler that reads the request is always dynamic. Don't add `export const runtime` or `export const dynamic`: Next 16 rejects both when `cacheComponents` is on, which `create-next-app` enables by default. ### The session `session(request)` is the only place the server learns who is asking: the device never says who it is. It runs on every request, and every few minutes on an open WebSocket. Return `null` when nobody is signed in, or: | Field | Meaning | |---|---| | `viewer` | the id of the signed-in user's row in the viewer model | | `claims` | [claims](/docs/server/permissions#claims-facts-about-the-session) granted to this session: `[$support(isOnShift)]`; a grant made with `false` isn't granted | | `readOnly` | the session may read but not write: its writes are refused with `ReadOnly`, and the client's write methods throw `ReadOnlyError` | | `tenant` | for engine-owned tables split by tenant (see [Postgres](/docs/server/postgres#tenancy)); Prisma tables have one | The device learns the outcome: `db.$session.viewerId`, `db.$session.claims`, `db.$session.hasClaim($support)` and `db.$session.readOnly`. ### Options | Option | Default | Meaning | |---|---|---| | `session` | | the session callback above | | `anonymous` | `false` | `true`: a `null` session gets an anonymous, read-only session that sees only `$.public` rows, instead of 401. In development the handler warns when this and the rules disagree | | `readOnly` | `false` | every session on this route is read-only (below) | | `tokens` | | `{ secret, ttlSeconds? }`: adds `GET …/token`, which hands out short-lived sync tokens carrying the session, for live updates on another host. The secret needs at least 32 characters (`openssl rand -base64 32`). See [WebSocket](/docs/transports/websocket) | | `inlineSequencing` | `true` | order writes inside requests. Set `false` only when a background `engine.start()` runs elsewhere | | `warnUntracked` | on unless `NODE_ENV` is `production` | on the first request, warn about rows written outside clientdb that devices never receive. With the [change triggers](/docs/schema/prisma#writes-your-app-makes-with-prisma) installed there are none | | `cors` | off | `{ origin, credentials? }`: answer browser pages on other origins. See [Node.js servers](/docs/transports/node#clients-on-another-origin) | | `bodyLimit` | 16 MiB | larger request bodies get 413. A pull carries every write a device made offline, so keep it well above your largest backlog | `createFetchHandler` takes the same options. For a long-running Node.js server (node:http, Express, Fastify, Hono), see [Node.js servers](/docs/transports/node). ### Read-only routes A route with `readOnly: true` serves bootstraps, pulls, loads and queries, and refuses every write with `ReadOnly`, whatever the session says. Use it for a second endpoint, such as a wall display that shows a project's todos: ```ts title="src/app/api/display-sync/[...path]/route.ts" import { clientdbHandler } from "@clientdb/server/next"; import { getSyncSession } from "@/sync/session"; import { engine } from "@/sync/engine"; export const { GET, POST } = clientdbHandler(engine, { session: getSyncSession, readOnly: true, }); ``` The client for it passes `url: "/api/display-sync"` and `readOnly: true`, so its types have no write methods (see [Read-only clients](/docs/client/mutations#read-only-clients)). ## Any fetch-standard runtime `createFetchHandler` takes a `Request` and returns a `Response`. `verifyJwt` is a session callback that checks a bearer token from your auth provider: ```ts title="src/worker.ts" import { createFetchHandler, verifyJwt } from "@clientdb/server"; import { engine } from "./sync/engine"; const handler = createFetchHandler(engine, { // reads the bearer token, checks its signature and expiry session: verifyJwt({ jwks: "https://auth.example.com/.well-known/jwks.json", issuer: "https://auth.example.com", audience: "https://app.example.com", // the audience your app's tokens carry session: (claims) => { return claims.sub ? { viewer: claims.sub } : null; }, }), }); export default { fetch: (request: Request) => handler(request) }; ``` ## Endpoints All under the route's base URL (`/api/sync` above). The message shapes are in [Wire protocol](/docs/reference/protocol). | Request | Response | |---|---| | `GET /bootstrap` | NDJSON: `meta`, the rows of every eager model with their [eager relations](/docs/schema#eager-relations), `end`. `?models=a,b` sends only those models; `?load=lazy` only `meta` and `end`, for a client that loads every model when read | | `POST /pull` | NDJSON: `meta`, `actions`, then `end` with `syncId`, `confirmed` and `rejected`; or `reset` when the device must bootstrap again. Sends the device's unsent transactions first | | `POST /push` | `{ results: [{ clientTransactionId, ok, duplicate?, rejection? }] }` | | `POST /partial` with `{ loads: [{ model, field, key }] }` | `{ actions, covered }`: the rows of every load (the client batches the reads of one tick) and the loads they cover completely | | `GET /partial?model=&field=&key=` | the same for one load | | `POST /query` | one page of a [server query](/docs/client/queries#server-queries-rows-that-arent-on-the-device): `{ actions, covered, ids, cursor }`. Outside the model's `query` rules, 403 | | `GET /token` | `{ token, expiresAt }`, with `tokens` set | A request without a session gets 401 (unless `anonymous`). On the client, a 401 or 403 surfaces as a `SyncRequestError` whose `unauthorized` is true. ## The client HTTP sync is the client's default; there's nothing to turn on. ```ts title="src/sync/db.ts" "use client"; import { createDatabaseClient, indexedDb } from "@clientdb/client"; import { schema } from "./schema"; export const db = createDatabaseClient({ schema, storage: indexedDb(), // url defaults to "/api/sync", resolved against the page }); ``` | Option | Default | Meaning | |---|---|---| | `url` | `"/api/sync"` | the sync endpoint; relative URLs resolve against the page, absolute ones are used as is | | `live` | `false` | `true` adds a [WebSocket](/docs/transports/websocket) for instant updates; `{ url }` puts it on another host | | `network` | on | `false`: a local database with no server (tests, previews) | | `readOnly` | `false` | a client without write methods | | `load` | | `"lazy"`: treat every model as lazy, for a client that loads only what it reads | | `syncOnLoad` | `true` | pull right after start | | `syncOnFocus` | `!live` | pull when the window regains focus, becomes visible or comes back online | | `syncIntervalMs` | `30_000` without `live` | pull every N ms while the tab is visible (hidden tabs catch up on focus); `false` turns it off | | `pushOnWrite` | `true` | sync right after local writes | | `token` | | `() => token`, sent as `Authorization: Bearer …`, for other origins and native apps. Same-origin cookies need nothing | | `reconnect` | 250 ms to 10 s | `{ minDelayMs, maxDelayMs }`: backoff between retries | | `onError` | | network and storage errors; the client keeps retrying | ### Syncing on demand ```tsx title="src/app/projects/AddTodo.tsx" "use client"; import { db } from "@/sync/db"; import { addTodo } from "./actions"; // a server action that writes with Prisma export function AddTodo({ projectId }: { projectId: string }) { return ( ); } ``` - `db.$sync()` sends unsent writes and resolves once this device has everything the server committed before the call: it waits for a pull that started after the call (with a live socket, a barrier on the socket instead). Calls made meanwhile share one pull; other tabs ask the tab that holds the connection. - `db.$action(fn)` runs your server action (or tRPC mutation, or fetch), then does the same, so what it wrote is on this device when the promise resolves. It resolves to `fn`'s result. See [Server logic with `$action`](/docs/client/mutations#server-logic-with-action). ## Status and lifecycle ```ts import { db } from "@/sync/db"; db.$status; // "idle" | "loading" | "bootstrapping" | "connecting" | "online" | "offline" | "outdated" | "closed" await db.$ready(); // eager models usable, from storage or the network; starts the client db.$role; // "leader" | "follower": which tab holds the connection await db.$close(); ``` `"outdated"` means the server runs another protocol or schema version: reload the app. `$ready()` rejects then, and when the server refuses the session. ## Performance Through the fetch handler (the same code the Next.js route uses), without network latency: | Metric | Result | |---|---| | Push of one transaction incl. inline sequencing, p50 / p99 | 2.21 / 4.23 ms | | Pull with nothing new, p50 / p99 | 0.76 / 2.47 ms | | Push + pull in one request, p50 / p99 | 2.78 / 6.45 ms | | Pull after 1,000 changes (compacted, streamed) | 12.6 ms, 274 KB | | Throughput, 8 concurrent serverless instances | 1,184 tx/s | ## Mixing modes Both modes share the same log. A WebSocket server for live clients and serverless route handlers can run side by side, and `db.$sync()` works with `live: true` too. --- # Node.js servers: node:http, Express, Fastify and Hono > Run the sync endpoints and the realtime WebSocket on a plain Node.js server: node:http, Express, Fastify or Hono, with CORS, body limits and graceful shutdown. On a long-running Node.js server, `createSyncServer` serves the same HTTP endpoints as the [Next.js handler](/docs/transports/http) (`/bootstrap`, `/pull`, `/push`, `/partial`, `/query`, and `/token` with `tokens`) plus the [WebSocket](/docs/transports/websocket) at `/live`, all under one base path (`/api/sync` by default, which is where clients look unless you set their `url`). It also starts the engine's background sequencer, which live clients need. Every example below uses the same engine module and auth: ```ts title="src/sync/engine.ts" import { createEngine } from "@clientdb/server"; import { permissions } from "./permissions"; export const engine = createEngine({ permissions }); ``` The `session` callback reads who is signed in from the request headers, so it works on HTTP requests and on WebSocket upgrades alike. Express and Fastify middleware doesn't run for upgrades, so don't rely on what it adds to the request (`req.user`, `req.session`). ## node:http ```ts title="src/server.ts" import { createServer } from "node:http"; import { createSyncServer } from "@clientdb/server"; import { getSession } from "./auth"; // your auth library import { engine } from "./sync/engine"; const syncServer = createSyncServer(engine, { session: async (request) => { const session = await getSession(request.headers); return session ? { viewer: session.userId } : null; // the id of the signed-in user's row, or null }, }); const server = createServer((request, response) => { if (request.url === "/health") { response.end("ok"); return; } syncServer.middleware(request, response); // /api/sync/…, and 404 for anything else }); syncServer.attachWebSocket(server); // WS /api/sync/live server.listen(4000); ``` When the server does nothing else, `syncServer.attach(server)` does both lines at once. ## Express ```ts title="src/server.ts" import express from "express"; import { createSyncServer } from "@clientdb/server"; import { getSession } from "./auth"; // your auth library import { engine } from "./sync/engine"; const syncServer = createSyncServer(engine, { session: async (request) => { const session = await getSession(request.headers); return session ? { viewer: session.userId } : null; }, }); const app = express(); app.use(syncServer.middleware); // before express.json(): clientdb reads the body itself app.use(express.json()); // …your routes const server = app.listen(4000); syncServer.attachWebSocket(server); ``` The middleware answers requests under the base path and calls `next()` for everything else. Mounted as `app.use("/api/sync", syncServer.middleware)` it works the same. It also works with Connect and anything else that passes `(request, response, next)`. A body parser that runs first is fine too, but its own size limit (100 KB for `express.json()`) then applies. ## Fastify ```ts title="src/server.ts" import Fastify from "fastify"; import { createSyncServer } from "@clientdb/server"; import { getSession } from "./auth"; // your auth library import { engine } from "./sync/engine"; const syncServer = createSyncServer(engine, { session: async (request) => { const session = await getSession(request.headers); return session ? { viewer: session.userId } : null; }, }); const app = Fastify(); await app.register(syncServer.fastify); // /api/sync/*, WS /api/sync/live, closes with the app await app.listen({ port: 4000 }); ``` The plugin reads request bodies itself, but only in its own scope: the rest of your app keeps Fastify's parsers. Set the path with `basePath`, not with the `prefix` option of `register`. ## Hono On Node, Hono runs through the fetch handler; the WebSocket goes on the server `serve()` returns. ```ts title="src/server.ts" import { serve } from "@hono/node-server"; import { Hono } from "hono"; import { createSyncServer } from "@clientdb/server"; import { getSession } from "./auth"; // your auth library import { engine } from "./sync/engine"; const syncServer = createSyncServer(engine, { session: async (request) => { const session = await getSession(request.headers); return session ? { viewer: session.userId } : null; }, }); const app = new Hono(); app.all("/api/sync/*", (context) => { return syncServer.fetch(context.req.raw); }); const server = serve({ fetch: app.fetch, port: 4000 }); syncServer.attachWebSocket(server); ``` `syncServer.fetch` is the same fetch-standard handler as `createFetchHandler`, so it also fits Bun and other fetch-style servers. ## Options `createSyncServer` takes the [handler options](/docs/transports/http#options) (`session`, `anonymous`, `readOnly`, `tokens`, `inlineSequencing`, `warnUntracked`) and: | Option | Default | Meaning | |---|---|---| | `basePath` | `"/api/sync"` | where the endpoints and `/live` are served; the same as the client's default `url` | | `cors` | off | `{ origin, credentials? }`: let browser pages on other origins call the endpoints | | `bodyLimit` | 16 MiB | largest request body and WebSocket message; bigger ones get 413 | | `start` | `true` | start the engine's sequencer now and stop it in `close()`; `false` if you do both yourself | `cors` and `bodyLimit` work the same on `createFetchHandler` and the Next.js handler. ## Clients on another origin When the app's pages are served from another origin than the sync server, allow that origin: ```ts title="src/server.ts" import { createSyncServer, verifyJwt } from "@clientdb/server"; import { engine } from "./sync/engine"; const syncServer = createSyncServer(engine, { session: verifyJwt({ jwks: "https://auth.example.com/.well-known/jwks.json", audience: "https://app.example.com" }), // reads the bearer token cors: { origin: ["https://app.example.com"] }, }); ``` ```ts title="src/sync/db.ts" import { createDatabaseClient, indexedDb } from "@clientdb/client"; import { getToken } from "@/lib/auth-client"; // your auth library import { schema } from "./schema"; export const db = createDatabaseClient({ schema, url: "https://api.example.com/api/sync", live: true, token: () => { return getToken(); }, storage: indexedDb(), }); ``` `origin` takes one origin, a list, `"*"` or a function of the `Origin` header. Add `credentials: true` only if cross-origin requests carry cookies (it needs explicit origins). With `cors` set, WebSockets opened by pages on origins it doesn't allow are refused as well. Without it, a page on another origin may open the WebSocket only with a [sync token](/docs/transports/websocket#live-updates-on-another-host), never on the viewer's cookies: browsers attach cookies to WebSockets any site opens. ## Graceful shutdown ```ts process.on("SIGTERM", async () => { await syncServer.close(); // closes live sockets; clients reconnect to another instance server.close(); await engine.close(); }); ``` `close()` closes every WebSocket with code 1001, refuses new ones, and stops the sequencer it started. With Fastify, `await app.close()` does this for you. When `session` or the engine throws, the request answers 500 and the error is logged; the process keeps running. --- # WebSocket: realtime > Instant updates over a WebSocket, with catch-up on reconnect, sync tokens for a socket on another host, and sessions checked again while the socket is open. Live updates are off by default; `live: true` on the client opens a WebSocket. Changes then reach every device the moment the server has ordered them: in the benchmark, a write shows on another device in about 2 ms (p50). The examples use the todo app from the [quick start](/docs/quick-start). ## Server The socket needs a long-running process: `createSyncServer` on Node.js. It serves the same HTTP endpoints as the [Next.js handler](/docs/transports/http) plus `WS /live`, and starts the engine's background sequencer. ```ts title="src/server.ts" import { createServer } from "node:http"; import { createSyncServer, verifyJwt } from "@clientdb/server"; import { engine } from "./sync/engine"; const syncServer = createSyncServer(engine, { session: verifyJwt({ jwks: "https://auth.example.com/.well-known/jwks.json", issuer: "https://auth.example.com", audience: "https://app.example.com", // the audience your app's tokens carry session: (claims) => { return claims.sub ? { viewer: claims.sub } : null; // or look up the user row by an external id }, }), }); const server = createServer(); syncServer.attach(server); // /api/sync/… and WS /api/sync/live server.listen(4000); ``` For Express, Fastify, Hono, CORS and graceful shutdown, see [Node.js servers](/docs/transports/node). ## Client ```ts title="src/sync/db.ts" "use client"; import { createDatabaseClient, indexedDb } from "@clientdb/client"; import { getToken } from "@/lib/auth-client"; // e.g. Clerk's getToken(), Supabase's session.access_token import { schema } from "./schema"; export const db = createDatabaseClient({ schema, url: "https://api.example.com/api/sync", live: true, token: () => { return getToken(); // Authorization header over HTTP, ?token= on the socket }, storage: indexedDb(), }); ``` Browsers can't set headers on WebSockets, so the token travels as a query parameter there. The server reads `?token=` on WebSocket upgrades only, never on plain HTTP requests, since URLs end up in logs. Keep query strings of the `/live` path out of your proxy's access logs, or use short-lived sync tokens (below) so a logged token expires within minutes. ## Live updates on another host Often the app keeps its session cookie and its Next.js route, and only the socket runs elsewhere. The route then hands out short-lived **sync tokens**: signed tokens carrying the whole session (the viewer, claims, read-only and tenant), so the socket server never asks your app who is signed in. ```ts title="src/app/api/sync/[...path]/route.ts" import { clientdbHandler } from "@clientdb/server/next"; import { getSyncSession } from "@/sync/session"; // the session callback from the HTTP page import { engine } from "@/sync/engine"; export const { GET, POST } = clientdbHandler(engine, { session: getSyncSession, tokens: { secret: process.env.CLIENTDB_SECRET! }, // adds GET /api/sync/token }); ``` ```ts title="src/live-server.ts" import { createServer } from "node:http"; import { createSyncServer } from "@clientdb/server"; import { engine } from "./sync/engine"; // no session callback: every request carries a sync token signed with the same secret const syncServer = createSyncServer(engine, { tokens: { secret: process.env.CLIENTDB_SECRET! } }); const server = createServer(); syncServer.attach(server); server.listen(4000); ``` ```ts export const db = createDatabaseClient({ schema, live: { url: "wss://live.example.com/api/sync" } }); ``` The client fetches a token from `/api/sync/token` (with the page's cookie) and opens the socket with it. Long-lived credentials never end up in WebSocket URLs. ## Sessions are checked again while the socket is open A socket can stay open for hours, longer than a sign-in or a claim lasts. So the server checks its session again every `tokens.ttlSeconds` (5 minutes by default): - **Opened with a sync token:** the client fetches a new token before the current one expires and sends it over the socket; the server takes the new token's session. If the token expires without a new one, the server closes the socket. - **Opened otherwise** (a cookie, or your auth provider's token): the server calls your `session` callback again with the original upgrade request. When the claims or the read-only flag changed, the device receives the new session (`db.$session` updates) and the rows it gained or lost, as for any [access change](/docs/server/access-changes). When the user signed out, became someone else, or the token expired, the server closes the socket with code 4401 and the client reconnects with fresh credentials. ## What happens on the socket 1. The client sends `hello` with its protocol version, client id and the last sync id it has. 2. The server answers with its own `hello`, the verified session, then the catch-up: changes to the user's groups, the rows of newly granted groups, and the log since the device's sync id, compacted to the latest change per row, plus confirmations of transactions it already applied. 3. From then on the server sends a `packet` per batch of writes, and the client sends `transactions` as the user writes. Writes made while disconnected are sent again after reconnecting and applied once. `db.$sync()` on a live client sends a barrier, `{ t: "sync", id }`, instead of a pull. The server answers `synced` once the transactions the socket sent before it are applied and everything committed before it has been delivered, so `$sync()` and [`$action`](/docs/client/mutations#server-logic-with-action) resolve with the server's changes on the device. If the socket closes first, the client pulls over HTTP instead. ## Reconnects The client reconnects with backoff (`reconnect: { minDelayMs, maxDelayMs }`, 250 ms up to 10 s). `db.$reconnectNow()` skips the wait. Catching up on 1,000 changes made while offline took 7 ms in the benchmark. ## Swift on Linux `URLSession` WebSockets on Linux need a libcurl built with WebSocket support (Ubuntu's isn't). Without one, the Swift client falls back to polling. See [Swift](/docs/swift). --- # Migrations > Schema and permission changes roll out with clientdb migrate: a dry run first, then versioned migrations, online re-routing, recomputed memberships and pruning. Old clients reload. Every deploy runs one command after your database migrations. It brings clientdb's stored state in line with the new code: rows routed by changed rules move to the right devices, rows written outside clientdb are picked up, and old log entries are pruned. ```bash npx prisma migrate deploy npx clientdb migrate src/sync/engine.ts ``` ```text clientdb: migrated (applied nothing · rerouted todo · reconciled 3 todo · recomputed viewer groups) clientdb: pruned (1204 log entries · 380 transaction ids · archived 2 project) ``` The module is the one that exports your engine (add `--export ` when it exports more than one). The command runs `engine.migrate()`, then `engine.prune()` when the engine sets `retention`, prints what they did and closes the pool. It needs a direct database connection (see [Postgres and Neon](/docs/server/postgres#serverless-vercel-and-similar)). ## Dry run `--dry-run` prints what the command would do and changes nothing. Run it in CI or before a risky deploy: ```bash npx clientdb migrate src/sync/engine.ts --dry-run ``` ```text clientdb: dry run, nothing applied (would apply nothing · schema changes addField todo.dueAt · would reroute todo · would adopt nothing · no capture triggers on Tag (run npx clientdb-prisma triggers) · would prune 1204 log entries, 380 transaction ids, archived 2 project) ``` From code, `engine.migrationPlan()` returns the same as an object: pending migrations, schema changes, models to re-route, rows to adopt, missing capture triggers, and what pruning would delete. Its `refusal` says why `migrate()` would stop, or is null. ## Old clients reload, by design The schema has a stable hash, also computed per model and per field. It covers fields, relations (with `onDelete` and `eager`) and each model's `load` mode, so a client still running an older bundle can't, for example, treat a model that became lazy as fully on the device. Every bootstrap and pull carries the hash, and a client whose hash differs stops with `SchemaOutdatedError`. There are no compatibility shims or support windows: every client runs the current schema. On the client, `db.$status` becomes `"outdated"`. Show a "new version available" prompt and reload. With [storage](/docs/storage) on, only the models whose shape changed are dropped and fetched again (`GET …/bootstrap?models=…`); everything else stays on disk. ## What `engine.migrate()` does It takes a session lock, so concurrent deploys run it one at a time, and compares the stored schema and compiled rules with the current ones: - applies versioned migrations (engine-owned tables), once each, each in its own transaction; - re-routes models whose rules or shape changed, online, in batches. Changing only `load`, `eager` or `onDelete` needs no migration: it changes the hash clients compare, not the stored data; - recomputes everyone's groups when group kinds change; - on Prisma tables, syncs rows written outside clientdb that devices haven't received (seed scripts, tools that ran before the change triggers existed), as `engine.reconcile()` does. ```ts title="scripts/migrate.ts" import { engine } from "../src/sync/engine"; const { applied, rerouted, reconciled, viewersRecomputed } = await engine.migrate(); console.log({ applied, rerouted, reconciled, viewersRecomputed }); // reconciled: { todo: 3 }, rows per model await engine.close(); ``` Because every run reconciles, run it again after seeding a database without triggers. See [Writes made outside clientdb](/docs/guides/untracked-rows). ## Prisma tables `prisma migrate` owns all DDL. clientdb's part, per deploy, is the command above. - **New or removed models:** regenerate the [change triggers](/docs/schema/prisma#writes-your-app-makes-with-prisma) so every model's table has them, as a Prisma migration. The dry run lists tables without triggers. ```bash mkdir -p prisma/migrations/20261202_clientdb_triggers npx clientdb-prisma triggers src/sync/schema.ts > prisma/migrations/20261202_clientdb_triggers/migration.sql npx prisma migrate dev ``` - **Upgrading clientdb:** run `npx clientdb-prisma models` again and migrate, so clientdb's tables have every column the new version uses. `clientdb migrate` stops with an error naming any missing column. - **Data-only migrations** (`migrations` below, without `sql` DDL) also work on Prisma tables. ## Engine-owned tables With a TypeScript schema, clientdb owns the tables, and a schema change needs a versioned migration: `migrate()` refuses one without it, naming the changes. ```ts title="src/sync/engine.ts" import { createEngine, migration } from "@clientdb/server"; import { permissions } from "./permissions"; export const engine = createEngine({ permissions, migrations: [ migration(1, { name: "todo due date", sql: `ALTER TABLE m_todo ADD COLUMN "dueAt" bigint`, // with dueAt: t.timestamp().nullable() in the schema resync: ["todo"], }), ], }); ``` - `sql` runs in the migration's transaction; `run: async ({ client, engine }) => { … }` changes data in code instead. - `resync` lists models whose rows the migration changed in bulk: devices get the changed rows, or one reload of the model above `resyncInvalidateThreshold` rows. Outside migrations, `engine.resync(model)` does the same, and `engine.resync()` covers every synced model. ## Changing permissions Changing a read rule changes where rows go. `engine.migrate()` detects the new rules and re-routes the affected models online; devices receive the rows they gained and lose the ones they lost, like any [access change](/docs/server/access-changes). Renaming a rule's `name`, or changing the shape of a condition without one, creates a new group kind: `engine.migrate()` recomputes everyone's groups and re-routes the affected models. See [Group ids and names](/docs/server/groups#group-ids-and-names). --- # Archive vs hard delete > Archive hides a row everywhere and keeps it, reversibly, until retention deletes it; hard delete removes the row and the rows that cascade from it, and can still be undone. In the todo app, finishing a project shouldn't destroy it: people may want it back. Deleting a single todo, on the other hand, should simply remove it. clientdb supports both. ## Archive Archiving hides a row on every device and keeps it in the database. Mark the model archivable; it gets two fields, `archivedAt` and `archivedBy`. With Prisma, add the two columns to the model and set `archivable` in `fromPrisma`: ```prisma title="prisma/schema.prisma" model Project { id String @id @default(uuid()) name String inviteCode String @unique archivedAt DateTime? @db.Timestamptz(3) archivedBy String? members Member[] todos Todo[] } ``` ```ts title="src/sync/schema.ts" import { fromPrisma } from "@clientdb/prisma"; import { prismaModels } from "../generated/clientdb"; export const schema = fromPrisma(prismaModels, { omit: { User: ["passwordHash"] }, models: { User: { load: "eager" }, Project: { load: "eager", archivable: true }, Member: { load: "eager" }, Todo: { load: "eager" }, }, }); export type Schema = typeof schema; ``` A model without both columns is a type error that names them. In a [TypeScript schema](/docs/schema), pass `{ archivable: true }` to `model()`, which adds the fields itself. Who may archive is the `archive` rule, for archiving and unarchiving alike: ```ts // in projectRules, src/sync/permissions/project.ts archive: { when: (project) => { return isAdmin(project); }, }, ``` On the device: ```tsx title="src/app/projects/ArchiveButton.tsx" "use client"; import type { Project } from "@/sync/db"; export function ArchiveButton({ project }: { project: Project }) { if (project.isArchived) { return ; } return ; } ``` - Default collections hide archived rows: `db.project.all` leaves them out, `db.project.archived.all` lists only them, `db.project.includeArchived().all` both. - Archived rows keep syncing, so "Restore" works on every device. A row counts as archived while any row it cascades from (`onDelete: Cascade` in `schema.prisma`, `onDelete: "cascade"` in a TypeScript schema) is, so a project's todos and their comments are hidden with it. - `archivedBy` is the id of the user who archived the row, and `archivedAt` the server's time; the server sets both from the session and its own clock, whatever the device sent, so retention can't be tricked into deleting a row early. A device that creates or restores a row already archived needs the `archive` rule as well as `create`. - Archiving is undoable like any change, and Prisma writes to `archivedAt` sync like any other column. ### Deleting archived rows after a while Archived rows are kept until `retention.archived` on the engine deletes them: ```ts title="src/sync/engine.ts" import { createEngine } from "@clientdb/server"; import { permissions } from "./permissions"; export const engine = createEngine({ permissions, retention: { log: "30d", archived: "90d" }, }); ``` `engine.prune()` (and `npx clientdb migrate`, after migrating) then deletes rows archived more than 90 days ago, with the rows that cascade from them, and the deletes sync to every device. A row that a `restrict` relation still points at stays, and is counted in `archivedKept`. See [Retention](/docs/server/engine#retention) for running it on a schedule. ## Hard delete ```ts const { undoable, unloadedDescendants } = todo.delete(); ``` A hard delete: - removes the row; - deletes the rows whose relation to it says `onDelete: "cascade"` (`onDelete: Cascade` in `schema.prisma`), and theirs in turn; - sets nullable references with `onDelete: "setNull"` to null; - fails with `Conflict` while a `restrict` relation points at the row. On every device that held the row, the delete removes it and its cascading children and leaves a tombstone, so a late update can't bring it back. ### Undoing a delete Undo restores the row and its cascading children with their original ids, and points the references that were set to null back at it. It is only complete if all of them were on this device: comments are lazy, so a todo's comments may not be. `delete()` reports this as `undoable` and `unloadedDescendants`. Pass `ensureUndoable` to fetch what's missing first, in one request; the row then disappears after that round trip instead of at once: ```ts const { undoable } = await todo.delete({ ensureUndoable: true }); // undoable: true ``` ## Which one to use | | Archive | Hard delete | |---|---|---| | Row stays in the database | yes, until `retention.archived` | no | | Still syncs | yes, hidden by default | no | | Cascading children | count as archived | deleted | | Undo | always | complete when the children were on the device | | Permission rule | `archive` | `delete` | --- # Errors and warnings > Every error code and development warning clientdb produces, what it means and how to fix it. ## Rejection codes A transaction the server refuses is dropped from the device's pending changes (they disappear from the screen), `handle.confirmed` rejects with a `TransactionError`, `db.$onTransactionError` listeners and the `onTransactionError` option are called, and the transaction leaves the undo history. On the server, `hooks.onWriteRejected` receives the session, code, model, operation and failed branches. | Code | Meaning | Fix | |---|---|---| | `Forbidden` | a write rule refused it; the message names the branches that failed, e.g. `Forbidden: todo.delete (author: no, admin: no)`, or for an update the fields no group allows (`todo.update isPrivate (not in any update group)`) | check the model's `create`, `update`, `delete` or `archive` rule; `when` must hold before and after an update | | `Forbidden` (enforce) | `todo.authorId must equal the viewer's id (got "…")` | send the enforced value from the device: `authorId: db.$session.viewerId` | | `Forbidden` (restricted field) | `project.update inviteCode (the viewer can't read it)`, even when the value sent is the stored one | only viewers who can read a restricted field may change it, or name it in an update | | `ReadOnly` | the session is read-only: the route says `readOnly: true`, the session callback returned `readOnly: true`, or the session is anonymous | expected; the client's write methods throw `ReadOnlyError` before sending | | `Validation` | an unknown field or model, a missing required field, a value that doesn't fit the field (`todo.done must be a boolean (got "yes")`: the wrong type, a value outside an enum, or null in a field that isn't nullable), a `validate()` message, a generated field, a changed primary key, or a value a database constraint refused | fix the input; the message names the field, or for database constraints the operation and model | | `Conflict` | a create with an existing id, a value another row already holds in a unique field, or a delete of a row that `restrict` relations still point at | use a new id or value, or delete or re-point the referencing rows | | `NotFound` | an update or delete of a row that doesn't exist, or that the viewer can't read (refused alike) | the row was deleted meanwhile, or the viewer lost access to it | | `AccessLost` | the device lost read access to a row it had unsent changes on (issued on the device; the whole transaction is refused, including its changes to rows it still reads) | expected after a demotion or removal; redo the changes that still apply | | `SchemaOutdated` | the device's schema differs from the server's | reload the app | | `Stale` | a resend the server may have applied already, after `retention.transactions` deleted its id: the device kept trying to send it, unconfirmed, for longer than that | expected after very long offline periods; raise `retention.transactions` to make it rarer | ## Client errors | Error | When | Fix | |---|---|---| | `ReadOnlyError` | a write on a read-only client: `This client is read-only (createDatabaseClient({ readOnly: true }))`, `(anonymous session)` or `(the server's session is read-only)` | check `db.$session.readOnly` before showing write controls | | `SyncRequestError` | the server answered a sync request with an error status; `status` holds it, and `unauthorized` is true for 401 and 403. `db.$ready()` rejects with it when the server refuses the session | sign in again; for other statuses the client retries | | `SyncRequestError` from `query()` | `query failed: 403 Forbidden: todo.title isn't queryable: list it in todo's query.fields`, or 400 `Validation` for a `limit` over `maxLimit` or a malformed query | list the field and operator in the model's [`query` rules](/docs/server/permissions#server-queries) | | `SchemaOutdatedError` | a bootstrap or pull reports another schema hash; `db.$status` becomes `"outdated"` | reload; ship clients and server together | | `ProtocolMismatch` | the server speaks another protocol version | reload | | `TransactionError` | `handle.confirmed` of a refused transaction; `rejection` holds the code and message | see [Rejection codes](#rejection-codes) | | `createDatabaseClient: url "…" is relative and there is no page location to resolve it against` | a relative `url` outside a browser (tests, Node, React Native) | pass an absolute URL | | `useLive is not used with MobX reactivity` | `useLive` inside a client using `mobxReactivity` | use `observer()` (or `live()`) and read directly | ## Server errors | Error | When | Fix | |---|---|---| | `AccessCompileError` | a read rule can't be routed, at engine creation | see [What the compiler rejects](/docs/server/groups#what-the-compiler-rejects) | | `AccessCompileError` (no viewer condition) | a read branch like `todo.isPrivate.is(false)` alone would show rows to every signed-in user | write `$.and($.authenticated, …)`, or `$.public` to include anonymous visitors | | `401` | your `session` callback returned `null`, and the route doesn't set `anonymous: true` | check the session cookie or bearer token; the server reads `?token=` only on WebSocket upgrades, so HTTP requests send `Authorization: Bearer` | | `415` | a `POST` whose body isn't `Content-Type: application/json`; clientdb's clients always send it | send JSON with that header. Other media types are refused so other sites can't post forms with the viewer's cookies | | `403` on the WebSocket | a page on another origin opened it with the viewer's cookies: without `cors`, other origins need a sync token, and with `cors`, an origin it allows | serve the page from the sync server's origin, add the page's origin to `cors`, or use [sync tokens](/docs/transports/websocket) | | `…: the secret must be at least 32 characters` | `tokens.secret` or `verifyJwt({ secret })` is short enough to guess from a token | generate one with `openssl rand -base64 32` | | `403` / `400` on `POST /query` (`QueryError`) | a query outside the model's `query` rules, or malformed | see the client's `SyncRequestError` above | | `503` with code `NotMigrated` | `clientdb: refusing to serve clients: …. Run \`await engine.migrate()\` (e.g. in your deploy step) and retry.` The route refuses to serve until `engine.migrate()` has run against the current schema and rules | run `npx clientdb migrate` in your deploy step; after upgrading clientdb, run `npx clientdb-prisma models` and migrate first | | `503` with code `Unavailable` (`Unavailable`) | the database failed in a way a retry can fix (lost connection, shutdown, timeout, contention), or another process's `migrate()` switched the database to other rules or another schema than this process was built with. Nothing was refused: clients keep their writes and retry, and live sockets close with code 1011 and reconnect | transient errors need nothing; a process still running the previous release keeps answering this until it is replaced | | `clientdb: refusing tenant "…": external tables hold the rows of the default tenant only` | a session or server write names a tenant while the engine serves Prisma-managed tables | keep `tenant` out of sessions, or serve tenants with engine-owned tables | | `… has no field_readers column: replace the clientdb models in schema.prisma with the current \`npx clientdb-prisma models\`` | clientdb's tables predate this version | re-run `npx clientdb-prisma models`, then `prisma migrate` | | `fromPrisma: User.apiToken looks secret …` | a synced column's name matches token, secret, hash, password, salt or key, and is in none of `omit`, `models..restricted` or `notSecret` (also a type error) | `omit` keeps it on the server, `restricted` sends it only where a field rule allows, `notSecret` sends it to every reader | | `models.Project.archivable: Project can't be archivable without the columns archivedAt DateTime? and archivedBy String?` | an archivable Prisma model lacks the columns (also a type error) | add them to `schema.prisma` | | `definePermissions: no read rule for …` | outside production, a synced model has no `read` rule | add `defineModelRules(schema, "model", { read: … })` (`$.canRead(row.parent)` to read like its parent), or mark the model `serverOnly` if it never syncs | | `…: the schema has no viewer model` | rules use `$.viewer`, but no model is named `user` and `createSchema` / `fromPrisma` has no `viewer` option | name the model whose rows are users with `viewer` | | `Schema changed without a migration: …` | engine-owned tables, and the schema changed with no versioned migration | add a `migration(…)` (see [Migrations](/docs/server/migrations#engine-owned-tables)) | | `engine.migrate() needs a direct database connection` | the database URL goes through a transaction pooler and `DIRECT_URL` isn't set | set `DIRECT_URL` (or the `directUrl` option) to the direct URL | | `createEngine: pass \`database\` (a Postgres URL or a pg.Pool), or set DATABASE_URL` | no `database` option and `DATABASE_URL` is empty | pass `database` or set the variable | | `createEngine: retention.log must be at least "1h"` | a shorter log retention | processes following the log need at least an hour | | `createEngine: retention.transactions must be at least retention.log` | transaction ids kept for less time than the log | keep them at least as long, so a device the log can still catch up resends safely | | `fromPrisma` errors | unsupported Prisma shapes, named in the message: ids that aren't `String`, composite foreign keys, `@map` on enum values, `Bytes` and other unsupported types, unknown `@default` functions | omit the field or exclude the model | ## Development warnings **Unhandled rejections** (every rejection nobody handles; in production only `Forbidden`, `Validation`, `Stale` and `AccessLost`, which the device issues itself): ```text clientdb: the server rejected a transaction (Forbidden: todo.delete (author: no, admin: no)); its optimistic changes were undone. ``` Handle them with `useTransactionErrors`, `db.$onTransactionError` or the `onTransactionError` option, or await `confirmed`. See [Transactions](/docs/client/transactions#rejections). **Untracked reads during render** (`@clientdb/react`, once per `model.property`): ```text clientdb: todo.title read during render outside useLive()/live(); this component won't update when it changes. Read it inside useLive(() => …), or wrap the component in live() (observer() with MobX). ``` See [Reactivity](/docs/client/reactivity#the-untracked-read-warning). **Mismatched `computed` / `effect`** (once): an `effect` or `computed` from `@clientdb/client` read data of a client that uses MobX reactivity. ```text clientdb: an effect() or computed() from @clientdb/client read data of a client that uses mobx reactivity, so it won't re-run when that data changes. Use db.$computed() and db.$effect(), which follow the client's reactivity. ``` See [Reactivity](/docs/client/reactivity#outside-react). **Untracked rows and missing triggers** (`clientdbHandler`, `createFetchHandler` and `createSyncServer`, first request, unless `NODE_ENV` is `production` or `warnUntracked: false`). With the change triggers installed neither occurs: ```text clientdb: 3 todo rows are not tracked (written outside clientdb, e.g. by a seed script), so clients never receive them. Run engine.migrate() (or engine.reconcile()) to sync them, and capture future writes with the triggers from `npx clientdb-prisma triggers`. clientdb: writes to Tag made outside clientdb (Prisma Client, SQL) won't reach clients: their tables have no clientdb capture triggers. Save the output of `npx clientdb-prisma triggers` as a migration, or call engine.changed() after such writes. ``` See [Writes made outside clientdb](/docs/guides/untracked-rows). **`anonymous` and the rules disagree** (the handler, outside production): ```text clientdb: some read rules use $.public, but this handler answers signed-out requests with 401, so nobody signed out sees those rows. Pass `anonymous: true` to serve them. ``` **Large bootstraps** (once per user, above `bootstrapRowWarning`, default 20,000 rows): ```text clientdb: a bootstrap for viewer u_42 sent 31,200 eager rows (todo: 28,000, comment: 3,200). Make large models lazy, or raise bootstrapRowWarning. ``` See [Load modes](/docs/schema#load-modes). **`verifyJwt` without `audience`** (outside production): a JWKS-verified token without an audience check accepts tokens your auth provider issued for your other apps. Pass the audience your app's tokens carry. --- # Benchmarks > Scale, server, socket-free, Prisma and client numbers: single machine, local Postgres 16, Node 22. Everything runs on one machine with no network latency, so the numbers measure engine and database work, not the network. All of them were measured on the same 4-core VM (16 GB, Node 22, Postgres 16 on the same machine), except the previous core's numbers in parentheses in the client table, which are recorded in `bench/baseline/`. Throughput is bounded by the single local Postgres and varies by roughly ±10% between runs. ## At scale: Prisma writes fanned out to thousands of clients `CLIENTDB_TEST_PG=… yarn bench:scale` (`bench/scale/`, described in `bench/README.md`): an issue tracker in Prisma-managed tables with capture triggers and a `defineRule` membership rule (a viewer reads the teams it belongs to; every user is in two of 200 teams). Writers (55% issue updates, 30% new comments, 10% new issues, 5% both in one transaction) go through Prisma Client at a fixed rate; the sync server runs `engine.start()`; simulated clients speak the wire protocol from separate processes, and 20 real clients with full replicas confirm the simulated latencies (p50 / p99 3.2 / 6.2 ms simulated, 3.3 / 6.6 ms real at 300 writes/s). Everything shares one 4-core VM (16 GB) with Postgres 16: `shared_buffers` 2 GB, `random_page_cost` 1.1, `synchronous_commit` and `fsync` on. **Commit → visible** is from the writer's commit to the client receiving the change, on loopback. 10,000 users, 130,000 rows, ~1,400 rows per viewer unless noted. | Write rate, 1,000 WebSocket clients | Commit → visible p50 / p95 / p99 | Server CPU | Postgres CPU | |---|---|---|---| | 300 writes/s | 3.3 / 5.3 / 6.6 ms | 26% | 57% | | 1,000 writes/s | 6.2 / 8.8 / 10.2 ms | 41% | 88% | | 3,000 writes/s | 20.3 / 31.9 / 48.9 ms | 50% | 128% | | 5,000 writes/s (saturated: 4,297 achieved) | 70.6 / 106 / 122 ms | 52% | 150% | CPU is in percent of one core. Postgres is the limit, at about 4,300 Prisma writes/s on this machine. | Connected clients, 300 writes/s | Commit → visible p50 / p99 | Server CPU | |---|---|---| | 1,000 WebSocket | 3.2 / 6.1 ms | 25% | | 10,000 WebSocket | 4.0 / 12.4 ms | 50% | | 20,000 WebSocket | 10.7 / 23.6 ms | 77% | | 5,000 polling over HTTP every 5 s | 2.6 / 5.0 s | 56% | | 10,000 polling every 5 s | 3.0 / 5.9 s | 87% | | Other | Result | |---|---| | 1,000 clients bootstrapping at once (~1,300 rows each) | 8.4 s; 3.4 s with `MemorySnapshotStore` | | One bootstrap, warm database / first after a fresh database copy | 50–60 ms / ~1.1 s | | 300 writes/s with 24,000 rows per viewer (500 members per team, 30,000 deliveries/s) | p50 / p99 3.9 / 8.0 ms | | 1m-row tables, same rows per viewer: 300 / 3,000 writes/s, p50 | 3.1 / 17.8 ms | | 10m-row tables, same rows per viewer: 300 / 3,000 writes/s, p50 | 3.3 / 21.5 ms | | Adopting existing rows (`engine.migrate()`): 1m / 10m rows | 84 s / 9.1 min | ## Server `CLIENTDB_TEST_PG=… yarn bench:server`: the issues example with 20,000 visible and 5,000 hidden issues in one team. One admin and one member client are connected. | Metric | Result | |---|---| | Seeding through the engine (routing + outbox, 500 rows/tx) | 4,214 rows/s | | Cold bootstrap in process, admin (25,000 issues) | 195.8 ms | | Cold bootstrap in process, member (20,000 issues) | 134.8 ms | | HTTP NDJSON bootstrap into a client, admin: cold / warm snapshot cache | 198.2 / 78.3 ms | | Write latency (permission checks + routing + outbox), p50 / p99 | 1.70 / 3.90 ms | | Commit → visible on another client (WebSocket), p50 / p99 | 2.63 / 5.49 ms | | Throughput, background sequencer, 16 concurrent writers: committed / delivered | 1,965 / 1,962 tx/s | | Catch-up after 1,000 changes offline (WebSocket reconnect) | 7.6 ms | | Promote → all 5,000 hidden issues usable on the member's client | 51.6 ms | | Demote → hidden issues evicted | 18.7 ms | | Hide one issue → move-out on the member's client | 3.9 ms | | Hide an issue with 2,000 comments: per-row re-route / set-based subtree re-tag | 63.5 / 43.2 ms | ## Socket-free mode No `engine.start()`, sequencing inline in requests. Measured through the fetch-standard handler (the same code the Next.js route handlers use). | Metric | Result | |---|---| | Push of one transaction incl. inline sequencing, p50 / p99 | 2.69 / 4.43 ms | | Pull with nothing new, p50 / p99 | 1.01 / 1.95 ms | | Push + pull in one request, p50 / p99 | 3.76 / 5.58 ms | | Pull after 1,000 changes (compacted, streamed) | 12.9 ms, 273 KB | | Throughput, 8 concurrent serverless instances | 1,184 tx/s | Inline sequencing passes are serialized by a transaction-scoped advisory lock (that keeps ids in commit order), which caps throughput below the background sequencer. ## Prisma-managed tables `yarn bench:prisma`: ShareKit's schema and permissions on engine-owned tables vs Prisma's tables; 10,000 uploads with one file each in one team. | Metric | Engine-owned tables | Prisma-managed tables | |---|---|---| | Bootstrap of a team member (20,000 rows) | 254.9 ms | 273.2 ms | | Client update, confirmed, p50 / p99 | 2.76 / 4.36 ms | 3.46 / 7.78 ms | | Client create until sequenced, p50 | 0.98 ms | 3.35 ms | | Adopting 20,000 existing rows (`engine.migrate()`) | n/a | 1.61 s | | App write with Prisma, p50: plain / with `engine.changed` | n/a | 1.31 / 5.25 ms | On Prisma tables each write also updates a side-table row and each read joins it, about 0.5 to 1 ms per write. ## Client `yarn bench` (Node 22, `--expose-gc`). 100 owners and N dogs with 4 fields, indexed by `ownerId`. Numbers for the previous MobX-based core in parentheses. | Backend | Rows | Ingest µs/row | Create µs/row | Heap B/row | First indexed query ms | 100 indexed queries ms | Observed field write µs | |---|---|---|---|---|---|---|---| | signals | 10,000 | 0.81 | 9.39 (30.98) | 209 (8,531) | 3.89 (18.8) | 1.25 (22.9) | 12.1 | | signals | 50,000 | 0.50 | 9.25 (30.47) | 193 (8,517) | 0.09 (116.8) | 7.35 (372.8) | 10.8 | | signals | 100,000 | 0.88 | 10.05 (26.61) | 193 (4,321) | 0.15 (236.5) | 12.2 (1,499.5) | 16.1 | | mobx | 10,000 | 0.50 | 10.99 (30.98) | 203 (8,531) | 0.08 (18.8) | 5.32 (22.9) | 11.2 | | mobx | 50,000 | 0.73 | 10.45 (30.47) | 193 (8,517) | 0.21 (116.8) | 11.4 (372.8) | 10.9 | | mobx | 100,000 | 1.07 | 10.92 (26.61) | 193 (4,321) | 0.21 (236.5) | 16.4 (1,499.5) | 23.8 | - **Ingest** is the bootstrap path: rows as arrays, no entity objects. - **Create** is an optimistic local create: a transaction, an outbox entry and an undo record per call. - **Observed field write** is one assignment while an effect observes the field and a collection filtering on that column. Observed queries are maintained incrementally (O(log n) per affected query). ## Running them ```bash yarn bench # client CLIENTDB_TEST_PG=postgres://… yarn bench:server CLIENTDB_TEST_PG=postgres://… yarn bench:prisma CLIENTDB_TEST_PG=postgres://… yarn bench:scale # DATASET=1m|10m|wide, SUITES=rate,clients,poll,bootstrap,full ``` --- # FAQ and limits > Common questions, and what clientdb deliberately doesn't do (yet). ## Do I need WebSockets? No. The [Next.js handler](/docs/transports/http) syncs over plain HTTP: on load, on focus, after writes and on an interval. Add the [WebSocket server](/docs/transports/websocket) when you want instant push; both share the same log. ## Does it work on Vercel and Neon? Yes. Route handlers run on Node.js by default (no `runtime` export needed); use a small pool; the request path works through Neon's pooled URL. Run `engine.migrate()` over a direct connection. There are no replication slots, so Neon branch restores and scale-to-zero are fine. See [Postgres and Neon](/docs/server/postgres). ## Do I have to move my data? No. With Prisma, rows stay in Prisma's tables; the engine keeps its metadata in a side table and runs no DDL. `engine.migrate()` adopts existing rows (about 2 s per 20,000), and on every later run adopts rows written outside clientdb since. ## What if my server code writes with Prisma directly? That works without any clientdb calls in your write code. Install the triggers migration once (`npx clientdb-prisma triggers`), and Postgres records the ids of every changed row: Prisma writes (nested and `*Many` included), raw SQL, other services and `ON DELETE CASCADE`. The engine syncs them on the next pull or push, or immediately when `engine.start()` runs. Regenerate the migration when you add a synced model. As a safety net, `await engine.reconcile()` compares your tables with clientdb's last synced copies and syncs the differences; it also runs inside `engine.migrate()`, and you can run it from a cron. If you'd rather not use triggers, pass the changed ids yourself with `await engine.changed({ project: [project.id] })`, inside the write's transaction to make it atomic. See [Untracked rows](/docs/guides/untracked-rows). ## Where does server-side business logic go? In your own server actions, tRPC procedures or API routes, writing with Prisma as usual. On the device, wrap the call in `db.$action(…)`: it resolves once what the action wrote has synced to this device. See [Server logic with `$action`](/docs/client/mutations#server-logic-with-action). ## How is this different from caching API responses? There are no per-endpoint queries to keep fresh. Each client holds a replica of exactly the rows it may read, and the server pushes precise deltas, including when access changes. Reads never wait on the network. ## Can a client see data it shouldn't, even briefly? The engine never sends a row to a user whose groups don't include it, and a [restricted field](/docs/server/permissions#restricted-fields) only to users its field rule allows. Rows that leave a device go as id-only deletes. Property tests check this against a reference implementation of the rules after every simulated step. ## What happens when two people edit the same field? The last write committed on the server wins, per field, on every client. Edits to different fields of the same row never conflict. See [Conflicts](/docs/server/conflicts). ## What about old app versions? They reload. A schema hash mismatch puts the client in `outdated` state. There are no compatibility windows by design. ## My component doesn't update when data changes `useLive` tracks only what its function reads. Fields and relations you read from its result while rendering aren't tracked; wrap that component in `live()`. In development, clientdb logs a warning naming the read. See [Reactivity](/docs/client/reactivity#live). ## My read rule fails with AccessCompileError Every read branch needs a viewer condition. For data every signed-in user may read, write `$.and($.authenticated, …)`; for anonymous access, `$.public`. See [Permissions](/docs/server/permissions#every-signed-in-user-and-anonymous-visitors). ## Can I use it without React? Yes. Reads and writes are plain synchronous calls, and `computed` and `effect` from `@clientdb/client` work anywhere (from `@clientdb/mobx` with a MobX client). With MobX, every surface is observable. See [Outside React](/docs/client/reactivity#outside-react). ## Limits - **Writes made outside clientdb need the triggers migration.** Without it, they sync only after `engine.reconcile()` or `engine.changed()` (the handlers warn about them in development). - **One tenant on Prisma tables.** Tenancy inside the app comes from your rules. Row-level security applies to engine-owned tables only. - **`fromPrisma` rejects** ids that aren't `String`, composite foreign keys, `@map` on enum values, `Bytes` and other unsupported types, and `@default` functions it doesn't know, with an error that names the field. - **BigInt** values beyond 2^53 lose precision on clients. - **Not built yet:** scale-out infrastructure (cells, tenant directory, posting-list delta index); a TC39 Signals adapter. - **Collaborative text editing** is out of scope; the design leaves room for it. --- # The sync model > How clientdb keeps every device's copy correct: one ordered log of changes, access groups, versions per row, and pending local changes. You don't need this page to use clientdb. It explains how things work inside, for when you're curious or debugging. The short version is [How it works, in 5 pictures](/docs/how-it-works). ## The architecture in one picture ```text browser tab(s) server (Node / Next.js route handlers) Postgres ┌───────────────────────────┐ pull/push ┌─────────────────────────────────────┐ ┌──────────────────────────┐ │ db.issue.where(…) (live) │ ──────────▶ │ permissions → compiled access plan │ │ app tables (yours/Prisma)│ │ optimistic tx, undo │ or WS live │ write: check rules, route rows to │─▶│ routing metadata │ │ IndexedDB, multi-tab │ ◀────────── │ groups, append to outbox │ │ clientdb_outbox → _log │ └───────────────────────────┘ per-viewer │ sequencer: outbox → ordered log │ │ clientdb_viewer_groups … │ deltas │ fanout: project log onto viewers │ └──────────────────────────┘ └─────────────────────────────────────┘ ``` A write travels like this: 1. A client applies a transaction optimistically and sends it. 2. The server checks the write rules, writes the rows, computes their routing groups and any viewer membership changes, and appends the resulting actions to the outbox, all in one Postgres transaction. 3. The sequencer moves committed outbox entries into the ordered sync log. 4. Each connected or pulling client receives the log entries projected for its viewer. Its own transaction comes back as confirmed, or as rejected with a reason. ## Sync log and sync ids Every change becomes part of one append-only, gap-free log (`clientdb_log`). Entries are numbered by a monotonically increasing **sync id**, one entry per write transaction. Sync ids follow commit order, so "everything after sync id N" is always well defined. A client stores the last sync id it applied (`db.$lastSyncId`), and resuming means asking for everything after it. ## Groups and routing Read rules compile into **group kinds**, such as `team.member(teamId)` or `team.admin(teamId)`. A **group** is a kind applied to one id, written as a key like `team.member|`. - Every synced row is tagged with the groups whose members may read it: its routing groups. - Every viewer has a set of groups they belong to. - A row reaches a viewer exactly when the two intersect. Membership comes from rows: a `teamMember` row with `userId = viewer` puts the viewer in `team.member|`. So the server knows which viewers a write affects without evaluating rules per viewer. A [claim](/docs/guides/permission-recipes#staff-and-other-facts-about-the-session) is a group too (`claim:staff`): the session callback grants it to a session, with no rows involved. Details in [Groups and routing](/docs/server/groups). A restricted field has its own read rule, so the server also records which groups may read it. A viewer in the row's groups but in none of the field's receives the row with that field left out (`undefined` on the client). ## Move-in and move-out Access changes in two ways, and both produce precise deltas: - **A membership change** (promotion, removal, new member) sends the viewer a `groups` action. For added groups the viewer receives their rows; for removed groups the client evicts every row that no longer intersects its groups. A claim the session callback stops granting works the same way. - **A row move** (a hidden issue, a changed team) re-tags the row. Viewers who gain it receive the full row; viewers who lose it receive an id-only delete marked `moved`. See [Move-in and move-out](/docs/server/access-changes). ## Bootstrap, catch-up and lazy loads - **Bootstrap** is a streamed NDJSON response: `meta` (sync id, groups, schema hash, and the session: viewer, claims, read-only), then the rows of every `eager` model, then the end marker. `db.$ready()` resolves once they are usable. - **Catch-up** happens on reconnect or pull. It sends the group delta, a snapshot of newly granted groups, then the log range **compacted** to the latest action per row, so clients never see superseded intermediate states. - **Lazy loads** fetch rows of a `lazy` model by a **load key** the first time a read needs them: an id (`get(id)`), a foreign key (`issue.comments`), a unique field (`where({ email })`), or the whole model (`db.comment.all`). Reads in the same tick share one request (`POST …/partial`). `preload()` starts a fetch early, as an optimisation. The client remembers which load keys it holds completely, and deltas keep them current. - **Eager-relation cascades**: when a load brings a parent row, the children of its `eager: true` relations come in the same response, and the load keys they complete (`issue.comments` of each issue) are marked as held. A cascade stops at 5,000 rows; what it didn't deliver loads when it's read. - **Server queries** (`db.issue.query({ where, orderBy, limit })`) ask `POST …/query` for one page of matching rows the viewer may read. The rows become ordinary rows on the device; the query keeps the page boundaries. - **Eviction**: with `eviction: { maxRows }`, the client drops the loads used longest ago as units once it holds more rows, and forgets that it held their load keys. Loads holding anything observed (a collection on screen, a row whose fields a component reads), eager models and rows with unsent writes stay. - **Invalidation**: after a bulk server-side change above a threshold, the server sends `invalidate` and the client re-fetches that model. - **Retention**: with `retention.log`, the server deletes old log entries. A client that last synced before the oldest kept entry gets a reset and loads afresh, keeping its unsent writes. Applied transaction ids are kept for `retention.transactions` (90 days by default): a write is applied at most once, and one resent after its id is gone that the server may have applied is rejected with `Stale`. ## Revisions and tombstones Every row has a **revision** drawn from one database sequence, bumped on each write and each routing change. The client applies a server row only if its revision is newer than the one it holds, so a row that arrives through two groups, or twice, is never applied twice or out of order. Hard deletes leave a client-side **tombstone**, so a stale upsert can't resurrect the row. Evictions caused by access changes are not tombstones: if access comes back, the row is delivered again. ## Optimistic writes and rebase The client keeps, per row, the **server base** and the stack of **pending transactions** that touch it. The visible row is the base with pending operations replayed on top. When a newer base arrives, pending writes are rebased onto it, so your local edit stays visible on top of other people's concurrent changes. See [Conflicts and rejections](/docs/server/conflicts). ## Schema hashes The schema has a stable hash (also per model and per field) over fields, relations including `onDelete` and `eager`, and load modes. A client whose hash differs from the server's gets `SchemaOutdatedError` and must reload: by design there is no support for old clients. See [Migrations](/docs/server/migrations). ## The layers of the client - **`Replica`** (`@clientdb/core`): pure and deterministic. It takes local transactions and server packets and returns change sets. No IO, no reactivity. Specified in [the protocol and spec](/docs/reference/protocol). - **`ClientView`** (`@clientdb/client`): entities, live queries and reactive atoms, updated from change sets. - **Drivers**: the sync client (HTTP and WebSocket), IndexedDB storage and multi-tab coordination. The Swift client follows the same split. --- # Groups and routing > How read rules compile into groups, how rows and viewers are tagged, and which rules the compiler rejects (and why). You don't need this page to use clientdb. It explains how things work inside, for when you're curious or debugging. The short version is [How it works, in 5 pictures](/docs/how-it-works). The engine never evaluates read rules once per user. Instead, when the engine is created, it turns every read rule from [Permissions](/docs/server/permissions) into three things: 1. **Group kinds**, such as `project.members` and `project.admin`. A group is one kind plus an anchor: `project.members|` is "the members of this project". 2. **Routing, per model**: which groups a row belongs to, computed from the row's own data. For the todo app: a todo with `isPrivate: false` goes to `project.members|`, and every todo goes to `user|` and `project.admin|`. 3. **Membership sources**: which rows decide who is in which group. A `member` row with `userId = X` and `role = "admin"` puts user X in `project.members|` and `project.admin|`. A row reaches a user exactly when the row's groups and the user's groups overlap. ```text todo T-2 { isPrivate: true, authorId: carol } ──route──▶ { user|carol, project.admin|launch } Alice (member, admin) ──member──▶ { user|alice, project.members|launch, project.admin|launch } ✓ receives T-2 Bob (member) ──member──▶ { user|bob, project.members|launch } ✗ never sees it ``` ## How rules become groups - `project.members.some((member) => { return member.userId.is($.viewer.id); })` compiles to one group per project. - A filter on the membership row, such as `member.role.is("admin")`, compiles to a separate group kind, so promotion and demotion are just a user joining or leaving a group. - `row.id.is($.viewer.id)` and `row.authorId.is($.viewer.id)` compile to one group per user. - Filters on the viewer's own row (`$.viewer.row.email.in(["ada@acme.com"])`) compile to groups computed from that row. - `$.public` compiles to one group for everyone, and `$.authenticated` to one for every signed-in user. - A claim compiles to one group per claim, `claim:support`, which the session joins while the callback grants the claim. - Each label in `$.anyOf({ … })` is one branch of the rule. Labels name branches in `explain()`, in errors and in `$.canRead(row, { except })`; they don't change which groups exist. - A [restricted field](/docs/server/permissions#restricted-fields) gets its own routing: the row records which of its groups may read each restricted field, and each user receives the row with only the fields their groups may read. Print the compiled plan with: ```ts title="scripts/explain.ts" import { compileAccess } from "@clientdb/server"; import { permissions } from "../src/sync/permissions"; console.log(compileAccess(permissions).explain()); ``` For the rules on the permissions page, it prints: ```text group kinds user ← user project.members ← member{userId=viewer} → project(projectId) claim:support ← claim project.admin ← member{userId=viewer, role="admin"} → project(projectId) routing (row → groups) project → project.members(id) project → claim:support(*) project.inviteCode → project.admin(id) todo → project.members(project) if isPrivate=false todo → user(authorId) todo → project.admin(project) comment → project.members(todo.project) if todo.isPrivate=false … ``` ## Group ids and names Every group kind has an id, and every row and user is tagged with keys built from it, such as `project.members|`. - **Without a name**, the id comes from the condition's shape, for example `project.members{role∈["admin"]}`. Identical conditions get the same id wherever you wrote them, so they share one group. - **With a name**, `defineRule(schema, "project", (project, $) => { … }, { name: "project.admin" })` uses `project.admin` as the id. It is readable in `explain()`, in errors and in the client's `db.$groups`, and it doesn't reveal rule details such as role names to the client. - **Ids are stored**: with every synced row, in each user's memberships, in the snapshot cache and on every device. Renaming a name, or changing the shape of an unnamed condition, makes a new group kind on the next `engine.migrate()`, which recomputes everyone's groups and re-routes the affected models. That runs online, but it isn't free. A fixed name avoids it when you only refactor how a rule is written. Names are optional. Set one for conditions that many models share, like project membership and admin roles. ## What this buys you - **Writes don't fan out per user.** Each write appends one group-tagged entry to the log, however many people can read it. - **Delivery is a set overlap check**, cheap enough to run for every connected device on every write. - **Access changes are exact.** A membership row changing means one user joins or leaves a group; a row's groups changing means the row arrives on or leaves exactly the devices on either side. See [When access changes](/docs/server/access-changes). - **Bootstraps can be cached.** A group's contents are the same for every member, so an optional `snapshotStore` holds them per (tenant, model, group), shared by all members, until any write touches the group. ## Deny groups With a `block` model (`userId` blocks `blockedUserId`), a user's todos can be withheld from the people they blocked: ```ts read: (todo, $) => { const blocked = todo.author.blocks.some((block) => { return block.blockedUserId.is($.viewer.id); }); return $.and($.not(blocked), isMember(todo.project)); }, ``` This compiles to a per-user deny tag: the row is withheld from blocked users even when another branch allows it. Blocking and unblocking remove the row from, or bring it back to, that user's devices. A deny must apply to the whole rule; the compiler checks this. ## Explicit groups For membership the rule language can't express, declare a group with your own membership function, in the `groups` option of `definePermissions`: ```ts title="src/sync/permissions/index.ts" import { definePermissions } from "@clientdb/server"; import { schema } from "../schema"; import { memberRules } from "./member"; import { projectRules } from "./project"; import { todoRules } from "./todo"; import { userRules } from "./user"; const AUDITOR_EMAILS = (process.env.AUDITOR_EMAILS ?? "").split(","); export const permissions = definePermissions(schema, [userRules, projectRules, memberRules, todoRules], { groups: { auditors: { // the anchors this user belongs to: "*" for a group without one members: async (viewer, db) => { const user = await db.get("user", viewer); return user && AUDITOR_EMAILS.includes(user.email as string) ? ["*"] : []; }, // which writes change whose membership ("*" = every user) affects: { user: (row) => { return row.id as string; }, }, }, }, }); ``` Rules refer to a group by name with `$.group`, alone or anchored at a field of the row; `definePermissions` fails on a name it doesn't define: ```ts read: (todo, $) => { return $.anyOf({ member: isMember(todo.project), auditor: $.group("auditors") }); }, // anchored: members() returns project ids, and the rule says which one the row needs read: (project, $) => { return $.anyOf({ member: isMember(project), guest: $.group("guests", project.id) }); }, ``` ## What the compiler rejects Every read rule must be routable. Rules are rejected with `AccessCompileError` when the engine is created if: - **A branch requires two separate memberships at once**, for example member of the project *and* of another team, in one array or `$.and`. That would need the overlap of two groups. Split it into separate `$.anyOf` branches, or use an explicit group. - **A comparison with the viewer is anything but equality with `$.viewer.id`**: no `isNot($.viewer.id)`, no ordering. Filters on the viewer's own row must compare its fields with literals. - **A membership row is filtered by something other than its own fields**, or by values that depend on the viewer. - **A `$.not` is anything but a whole-rule deny** of a single membership condition, that is `$.and($.not(…), $.anyOf({ … }))`. `$.not($.public)` and negated explicit groups are rejected too. - **A read branch has no condition on the viewer**, for example `todo.isPrivate.is(false)` alone, or `() => { return true; }`. That would let every signed-in user read the row (on Prisma tables, every user of the app). Write `$.and($.authenticated, todo.isPrivate.is(false))` if that is what you mean, or `$.public` to include anonymous sessions. A whole-rule deny counts as a condition; negating `$.authenticated` is rejected. - **One `name` is used for two different conditions.** For example, a rule named `project.admin` returning `$.or(member.role.is("owner"), member.role.is("admin"))` describes two membership paths under one name; write `member.role.in(["owner", "admin"])` instead. Two rules with the same `name` but different bodies are rejected too. - **`canRead()` references form a cycle**, or a relation is unknown. Write rules have none of these limits: they are evaluated in the write's transaction, not routed. --- # When access changes (move-in and move-out) > When someone gains or loses access, the engine sends exactly the rows to add and the ids to remove. No data ever reaches a device whose user may not read it. You don't need this page to use clientdb. It explains how things work inside, for when you're curious or debugging. The short version is [How it works, in 5 pictures](/docs/how-it-works). In the todo app, Alice adds Bob to the "Launch" project, later makes him an admin, and one day removes him. Each time, Bob's devices must end up holding exactly what the [rules](/docs/server/permissions) now allow him: the project's todos arrive when he joins, private todos and the invite code arrive when he becomes an admin, and everything leaves when he is removed. You write no code for this; the engine works it out from your rules, using the [groups](/docs/server/groups) they compile to. Access changes in three ways. ## Someone joins or leaves a group Adding a member, promoting or demoting one, or removing one changes which groups that user belongs to. Their devices receive a `groups` action: - **Added groups:** the device receives the rows of those groups for eager models, with their [eager relations](/docs/schema#eager-relations), in the same response (when pulling) or packet (over WebSocket). Lazy models aren't sent: what the device loaded of them reads as `"partial"` again, collections and server queries that something observes (a component on screen) load again at once, and the rest the next time they're read. - **Removed groups:** the device removes every row it can no longer reach through any of its groups. A transaction not yet sent that changes a removed row is refused whole with `AccessLost` (never sent, so its changes to rows the device still reads are undone too, and the rejection is reported); a transaction already sent waits for the server's answer. Lazy collections and server queries load again as for added groups, so a collection on screen settles as complete with the rows that remain. A load or server query page that was in flight when the groups changed is asked again, so rows the viewer just lost never land from an answer computed before. ```text Alice makes Bob an admin of Launch everyone in project.members|launch ← upsert member bob { role: "admin" } Bob ← groups { add: ["project.admin|launch"] } ← upsert todo T-2 (private todos of the project) ← upsert project launch (again, now with inviteCode) Alice makes Bob a plain member again Bob ← groups { remove: ["project.admin|launch"] } removes T-2; keeps project launch, without inviteCode ``` [Restricted fields](/docs/server/permissions#restricted-fields) follow the same groups: a row Bob already holds arrives again when a new group reveals one of its restricted fields, and a removed group hides the field while the row stays. The engine's `onAccessRemoved` hook is called with the session and the groups it lost (`reason: "rules"`), for audit logs. It receives group names, never row data. ## A claim is granted or withdrawn [Claims](/docs/server/permissions#claims-facts-about-the-session) come from your session callback, which the server asks again on every request and, on a live WebSocket, every few minutes. When the answer changes, the device gets the same `groups` action for the claim's group: support staff who go off shift lose the projects they could read only as support. `onAccessRemoved` is called with `reason: "claim"`. ## A row moves A write that changes which groups a row belongs to (making a todo private, moving it to another project) re-tags the row. One entry is logged with the old and new groups, and each device receives what its user is now allowed: | Recipient | Receives | |---|---| | in the new groups | the full row (for a move-in the row is complete, never a patch) | | only in the old groups | an id-only `delete` marked `moved: true`, with no data | | in neither | nothing | ```text Carol makes T-1 private (project.members|launch → user|carol, project.admin|launch) Carol, Alice ← upsert todo T-1 { isPrivate: true } Bob ← delete todo T-1 { moved: true } ``` A `moved` delete removes only that row from the device. A real delete also removes the rows that cascade from it, and leaves a tombstone so a stale update can't bring it back; a move leaves none, so if access returns, the row is delivered and applied again. ### Children follow their parent Children whose read rule is exactly `$.canRead(child.parent)` follow their parent. When a todo with 2,000 comments becomes private, the comments are re-tagged in bulk, one `UPDATE … RETURNING` per level, and users who lose the todo lose its comments with it. In the benchmark this takes 50 ms instead of 358 ms for re-routing row by row. ### Bulk changes Rows written outside clientdb and picked up with `engine.resync()` are re-routed the same way. Above `resyncInvalidateThreshold` rows of one model (default 10,000), devices get one `invalidate` for the model and reload it, instead of thousands of individual changes. ## While offline A device whose user was removed from a group and added back while it was offline receives, on reconnecting, the group change and the rows of the group as they are now, not a replay of history it had no access to. ## Speed From the server benchmark (a project with 20,000 todos everyone reads and 5,000 only admins read): | Change | Time until the user's device reflects it | |---|---| | Promote: 5,000 admin-only todos arrive | 31.5 ms | | Demote: admin-only todos removed | 12 ms | | Make one todo admin-only: move-out | 3.6 ms | ## Checked against a reference implementation Property-based tests run random sequences of writes, promotions, moves and reconnects against a reference implementation of the rules. After every step, each simulated device must hold exactly the rows the rules allow, and the wire must never carry data its recipient may not read. --- # Optimistic writes, conflicts and rejections > Pending writes are replayed on top of newer server data; conflicts resolve per field in commit order; refused transactions roll back cleanly. You don't need this page to use clientdb. It explains how things work inside, for when you're curious or debugging. The short version is [How it works, in 5 pictures](/docs/how-it-works). When Bob renames a todo, the new title shows on his screen at once, before the server has seen it. Meanwhile Alice may assign the same todo to someone, and the server may refuse Bob's change. This page explains how his device keeps the screen right through all of that. ## Server data plus pending changes For every row, the device keeps: - the **server base**: the last version the server confirmed; - the stack of **pending transactions** that touch it, in the order they were made; - an optional **draft** of unsaved edits (see [Edit, then save or revert](/docs/client/mutations#edit-then-save-or-revert)). The row your components read is the base with the pending changes replayed on top (and the draft, if any). ```text base (revision 7) { title: "Ship login", assigneeId: null } pending tx A set title = "Ship login page" visible { title: "Ship login page", assigneeId: null } server sends revision 8 { title: "Ship login", assigneeId: "alice" } ← Alice assigned it visible { title: "Ship login page", assigneeId: "alice" } ← A replayed on top ``` ## Replaying on newer data When a newer base arrives, pending changes are replayed on top of it, so a local edit stays visible over other people's changes. When the server confirms a transaction, it leaves the stack; its effect is now part of the base. A transaction is stored as the operations sent to the server. One step, `expand`, turns each operation into its effects on rows (deleting cascading children, `setNull`, `restrict`) and the steps to undo them. After a reload, the same step runs again on the stored outbox, so a pending delete hides its cascading children again. ## Conflicts Conflicts resolve **per field, in the server's commit order**: the last committed write wins. Two people editing different fields of the same todo never conflict. Two people editing the same field end up, on every device, with whichever transaction committed last. ## At most once Unconfirmed transactions are kept and sent again after reconnects, and across reloads when [storage](/docs/storage) is on. The server records each `(clientId, clientTransactionId)` it applied, so a resend of an applied one is confirmed without effect. These records are kept for `retention.transactions` (90 days by default, at least `retention.log`; see [The engine](/docs/server/engine#retention)). After that the server can't recognize a resend by its id. Every transaction carries the sync position the device had when it first tried to send it, and the server knows the highest position at which it applied a transaction whose id it deleted. A transaction it may have applied (its id is gone, and the device first tried to send it before that position) is refused with `Stale` and never applied twice. On Framecast: Olga promotes Max to admin on a train, the server applies it but its answer never arrives, and at her desk she makes Max a member again. If the laptop stays offline for longer than `retention.transactions`, its resend is refused with `Stale`, and Max stays a member; within that time it is confirmed without effect. So every transaction is applied at most once, and confirmed or rejected, never dropped silently. A `Stale` rejection means a write stayed unconfirmed on a device, which kept trying to send it, for longer than `retention.transactions`. ## Rejections If the server refuses a transaction, the whole transaction is dropped from the pending stack, so its changes disappear from the screen. Then `handle.confirmed` rejects with a `TransactionError`, `db.$onTransactionError` listeners are called, and the transaction leaves the undo history. On the server, the `onWriteRejected` hook is called. | Code | Meaning | |---|---| | `Forbidden` | a write rule refused it, or an update changed a field no `update` group allows; the message names the branches that failed, e.g. `Forbidden: todo.delete (author: no, admin: no)` | | `ReadOnly` | the session is read-only: the route says `readOnly: true`, the session callback returned `readOnly: true`, or the session is anonymous | | `Validation` | an unknown field or model, a missing required field, a value of the wrong type, a `validate()` message, a generated field or a changed primary key | | `Conflict` | a create with an existing id, or a delete of a row that `restrict` relations still point at | | `NotFound` | an update or delete of a row that doesn't exist, or that the viewer can't read (refused alike) | | `Stale` | a resend the server may have applied already, after it deleted the transaction's id ([above](#at-most-once)); it is not applied again | | `AccessLost` | the device lost read access to a row it had unsent changes on (issued on the device when the row is removed; the whole transaction is refused) | | `SchemaOutdated` | the device's schema differs from the server's | ## Write checks on the server Each transaction runs in one Postgres transaction: 1. A read-only session is refused before anything is read. 2. Every operation is checked against the schema. Fields are sent by name, so a device built for another schema version can't write the wrong column. 3. The [write rules](/docs/server/permissions) run against the row before and after: `when` must hold for both; each changed field must belong to an `update` group whose `when` holds; a changed restricted field must be readable by the viewer; `enforce` checks that fields hold their required value; `validate` runs last. 4. Rows are written, their groups and any membership changes worked out, and one outbox entry appended (see [Outbox and sequencer](/docs/server/outbox)). Serialization failures and deadlocks are retried automatically. ## Server logic: `$action` Some changes need server code: charging a card, sending an invite email. Those go through your own server action or API route, which writes with Prisma; the device then waits for the change to arrive with `db.$action(…)` (see [Server logic with `$action`](/docs/client/mutations#server-logic-with-action)). ## Collaborative text Character-level merging of text fields is out of scope. Last write wins is a per-field default, not a global assumption, so it can be added later. --- # Outbox and sequencer > How writes get a gap-free, commit-ordered sync id without replication slots: a transactional outbox drained by one sequencer. You don't need this page to use clientdb. It explains how things work inside, for when you're curious or debugging. The short version is [How it works, in 5 pictures](/docs/how-it-works). ## The problem If a client has applied sync id N, no action with an id below N may become visible later; otherwise a slow transaction that committed out of order would be skipped forever. A `bigserial` assigned inside the transaction follows *start* order, not commit order, so it can't be the sync id. A per-tenant counter row would serialize all commits. Logical replication slots are unsafe on Neon (idle slots are dropped, branch restores delete them). ## The design 1. **Write side.** Each write transaction appends its actions to `clientdb_outbox`, tagged with its transaction id. The outbox row takes effect only if the transaction commits. 2. **Per-row revisions.** Every synced row gets a revision from one database sequence on each write. Concurrent writers of a row are serialized by the row lock, so a row's revisions strictly increase. 3. **Sequencer.** It drains only *committed* outbox entries, assigns sync ids in commit order, and writes them to `clientdb_log`, one log row per transaction, in one database transaction. A transaction that commits later is sequenced later, so a hole can never appear behind a reader. 4. **Clients apply a row only if its revision is newer**, so the order of actions inside a pass doesn't matter for correctness, and re-deliveries are no-operations. ## Two ways to run it **Inline, inside requests** (the default for the HTTP and Next.js handlers). Each push sequences right after it commits, and each pull sequences before it reads. Passes from any number of serverless instances are serialized by a transaction-scoped advisory lock, so they are safe to run concurrently and work through a transaction-mode pooler. A quiet deployment needs no background process at all. **In the background** with `engine.start()`, woken by a Postgres notification when a write commits (from any process, and from the change triggers), with a 250 ms poll as the fallback. Use this with the [WebSocket server](/docs/transports/websocket). Other engine instances tail the log. You may then set `inlineSequencing: false` on HTTP handlers, though leaving it on is safe. | | Background sequencer | Inline (serverless) | |---|---|---| | Throughput (benchmark) | 1,965 tx/s, 16 writers | 1,184 tx/s, 8 instances | | Push p50 | 1.17 ms | 2.21 ms incl. sequencing | | Process needed | yes | no | Inline passes are serialized by the advisory lock, which caps throughput below the background sequencer's batching. ## Cost Per write transaction: your rows, plus one small outbox row (sharing the commit, so no extra fsync), moved to the log by the sequencer. On Prisma tables there is also one `clientdb_row` upsert per synced row. The outbox insert also sends a `pg_notify`, delivered on commit, which wakes the background sequencer. No logical replication, no extensions. Writes made outside clientdb take a similar path: the [change triggers](/docs/guides/untracked-rows) record the changed ids in a queue in the same transaction, and the engine drains that queue on the next pull or push (or right away with `engine.start()`), just like the outbox. ## Bootstrap splicing A bootstrap first reads the current head sync id, then opens a `REPEATABLE READ` snapshot. Everything sequenced at or before the head committed before the snapshot began, so it is in the snapshot; everything after gets a larger id and arrives as a delta. Actions seen twice are no-operations because of revisions. ## Snapshot cache validity With a `snapshotStore`, the sequencer records in `clientdb_group_touch`, in the same transaction as the log, which groups each batch touched. A cached per-group chunk is valid exactly until any action touches its group, so a cached snapshot is never stale. ## Log retention The log grows with every write until `engine.prune()` deletes entries older than `retention.log` (see [The engine](/docs/server/engine#retention)). A device that was offline longer than that can't be caught up from the log: the server answers with `reset` before applying anything the device sent, and the device bootstraps again, keeping its unsent changes, and sends them again (see [Wire protocol](/docs/reference/protocol#starting-over)). The ids of applied transactions, which keep a resend from applying twice, are kept longer: `retention.transactions`, 90 days by default (see [At most once](/docs/server/conflicts#at-most-once)). --- # Postgres, Neon and serverless > Runs on any Postgres 14+, including Neon with scale-to-zero and branch restores. Pooling, the tables clientdb adds, tenancy, row-level security and the snapshot cache. ## Any Postgres, Neon included The engine needs no logical replication and no extensions: an outbox table, sequences and advisory locks are enough. Writes send a `pg_notify` on commit that wakes `engine.start()`, which listens on its own connection; inline sequencing doesn't need it. It works on Neon, including scale-to-zero and branch restores, and on any managed Postgres. ## Serverless (Vercel and similar) - Use the **Node.js runtime** (the default for route handlers; `pg` needs TCP). On serverless hosts the engine keeps its pool small (5 connections, 10 elsewhere). - Request-time locks are transaction-scoped, so a **transaction-mode pooler** (Neon's pooled URL, PgBouncer) works for the route handlers. - `engine.migrate()` takes a session advisory lock, so it needs a **direct connection**: `DIRECT_URL`, Prisma's convention, or the `directUrl` option. A pooler URL is refused with a message saying so. Long-running WebSocket servers should use a direct connection too. ```ts title="src/sync/engine.ts" import { createEngine } from "@clientdb/server"; import { permissions } from "./permissions"; // DATABASE_URL may be the pooled URL; migrate() uses DIRECT_URL export const engine = createEngine({ permissions }); ``` ```bash DIRECT_URL=postgres://…direct… npx clientdb migrate src/sync/engine.ts ``` ## The tables clientdb adds With [Prisma](/docs/schema/prisma), your rows stay in your tables, and `npx clientdb-prisma models` adds these models to `schema.prisma`, so your migrations create them. With a TypeScript schema, `engine.migrate()` creates them, plus one table per model. | Table | Holds | |---|---| | `clientdb_outbox`, `clientdb_log`, `clientdb_head` | each write's changes, then the sync log in commit order (see [Outbox and sequencer](/docs/server/outbox)). `clientdb_log.created_at` lets `retention.log` prune it, and each entry's random `nonce` lets a server restored from a backup (or a Neon branch restore) tell positions from before the restore: devices past it load afresh, keeping their unsent writes | | `clientdb_transactions` | the ids of applied device transactions and the head each was applied at, so a resend applies once; pruned after `retention.transactions`, which moves `clientdb_head.transactions_horizon` (see [At most once](/docs/server/conflicts#at-most-once)) | | `clientdb_row` | for Prisma tables: each row's revision, groups, `field_readers` (who reads its [restricted fields](/docs/server/permissions#restricted-fields)) and a snapshot of its last synced values | | `clientdb_viewer_groups` | each user's groups | | `clientdb_group_touch` | the last write to each group, for the snapshot cache | | `clientdb_changes` | ids of rows changed outside clientdb, filled by the [change triggers](/docs/guides/untracked-rows) | The snapshot in `clientdb_row` is the "before" of the next write made outside clientdb: when Prisma changes a member's role, the engine compares it with the snapshot to work out who gained or lost access. Rows of `serverOnly` models keep a snapshot too, without ever being sent to a device, because rules read them: a membership in a `serverOnly` table still moves rows when it changes. After upgrading clientdb, run `npx clientdb-prisma models` again and migrate: `clientdb migrate` stops with an error naming any column the tables are missing. ## Tenancy Engine-owned tables are multi-tenant: every row, log entry and membership carries a tenant. Your session callback sets it, `session: async (request) => { return { viewer: user.id, tenant: user.orgId }; }`, and bootstraps, pulls, groups and the log are all scoped by it. Server writes name it: `engine.systemWrite(operations, { tenant })`. Prisma tables use a single tenant, and you never pass one: the engine refuses a session or write naming another tenant, loudly, rather than serve the one set of rows to both. Teams or workspaces inside your app are separated by your permission rules. ## Row-level security With `rowLevelSecurity: true`, every engine transaction sets `clientdb.tenant`, and Postgres policies keep queries inside that tenant, as defense in depth. ```ts const engine = createEngine({ permissions, rowLevelSecurity: true }); // your own queries, with the same guard await engine.withTenant(orgId, async (client) => { await client.query("SELECT …"); }); ``` Run the engine as a non-superuser role: superusers bypass row-level security. It applies to engine-owned tables only. ## Snapshot cache Bootstraps can be served from an optional `snapshotStore`: `MemorySnapshotStore`, `FsSnapshotStore`, or your own (for example object storage). It holds the rows per (tenant, model, group), shared by every member of the group, and each entry is valid until any write touches the group. ```ts import { createEngine, FsSnapshotStore } from "@clientdb/server"; const engine = createEngine({ permissions, snapshotStore: new FsSnapshotStore("/var/cache/clientdb") }); ``` In the benchmark, an admin's 25,000-row bootstrap over HTTP took 196 ms cold and 92 ms from a warm cache. ## What each write costs Your rows, plus one outbox row, moved to the log by the sequencer. On Prisma tables there is also one `clientdb_row` upsert per synced row, about 0.5 to 1 ms per write. Writes made outside clientdb add one small row per changed row to `clientdb_changes`, inserted by the change triggers once per statement, so bulk updates stay set-based. --- # Protocol and spec > The language-neutral contract between the server and every client: wire protocol v2, sessions, load keys, server queries, replica semantics, the schema IR and conformance vectors. You don't need this page to use clientdb. It's the contract for anyone writing another client, or debugging what goes over the wire. Everything a client implementation needs lives in the repo's `spec/` folder. The TypeScript client (`@clientdb/core`), the Swift client and the server's write checks are all tested against it. This page summarizes it; `spec/protocol.md` is the full text. | File | What | |---|---| | `spec/protocol.md`, `spec/protocol.schema.json` | Wire protocol v2: endpoints, NDJSON messages, encodings, sessions, rejections | | `spec/replica.md` | Replica semantics: rows, replaying pending changes, `expand` (cascades, `setNull`, `restrict`), drafts, undo, server input, change sets | | `spec/schema-ir.schema.json`, `spec/schemas/*.json` | The schema IR (`clientdb.schema.json`) | | `spec/vector.schema.json`, `spec/vectors/*.json` | Conformance vectors: steps plus the exact observation after each | ## Wire protocol v2 JSON everywhere; streams are NDJSON (one JSON value per line). `PROTOCOL_VERSION = 2` is sent in `meta`, the client's `hello` and pull requests. A server answers a mismatched version with an `error` (`code: "ProtocolMismatch"`). A schema hash mismatch makes the client stop with `SchemaOutdated` and reload. ### Encoding - **Rows down** (server → client) are arrays in schema field order, `id` first: `upsert.row`. Bootstrap rows are wire rows, `[...fields, revision, groups]`, followed by `fieldGroups` for models with restricted fields. - **Restricted fields** reach only the viewers their field rule allows. Every row of a model with restricted fields carries `fieldGroups`: the restricted fields the viewer reads, each with the viewer's groups through which it reads it. A restricted field missing from `fieldGroups` is hidden: its slot in the row is null, and the client stores it as undefined, not as null. - **Operations up** (client → server) are keyed by field name. The server checks every name, so a client built against another schema version can't silently write the wrong column. - Timestamps are epoch milliseconds; decimals are strings (`"49.00"`); JSON fields carry any JSON value. - **Generated fields** are filled in by the database. A client's `create` carries them as null and its `update` never names them; the server refuses either otherwise (`Validation`). The upsert of the created row carries the generated values. ### Endpoints All under the base URL (`…/sync`, `/api/sync` by default). | Request | Response | |---|---| | `GET /bootstrap` | NDJSON: `meta`; per eager model, `rows`* and `done`; then the eager-relation cascade under those rows (`rows`* per model) and one `covered` with its load keys; then `end`. `?models=a,b` sends only those models (a client refetching models whose hash changed), without a cascade. `?load=lazy` sends only `meta` and `end` | | `POST /pull`, `PullRequest` | NDJSON: `meta`; `actions`* (group changes, rows of newly granted groups with their cascade, the log since `since` compacted to the latest action per row; the first `actions` line carries the cascade's `covered`); `end` with `syncId`, `confirmed` and `rejected`. Or a single `reset` (see [Starting over](#starting-over)). Pushed `transactions` apply first | | `POST /push`, `{ clientId, transactions }` | `{ results: [{ clientTransactionId, ok, duplicate?, rejection? }] }` | | `GET /partial?model=&field=&key=` | `LoadResult`, `{ actions, covered }`: upserts for the visible rows of `(model, field = key)` (or the whole model without `field`) and their eager-relation cascade; `covered` lists the load keys the response delivered completely. `field` must be a load key of the model | | `POST /partial`, `{ loads: [{ model, field, key }] }` | the same for up to 1,000 loads at once (a client's reads in one tick), rows deduplicated | | `POST /query`, `QueryRequest` | `QueryResult`, `{ actions, covered, ids, cursor }`: one page of a [server query](#server-queries). Outside the model's query rules: 403 with `code: "Forbidden"`; malformed or over `maxLimit`: 400 with `code: "Validation"` | | `WS /live` | the client sends `hello`, then `transactions`, `token` (a renewed sync token) and `sync` barriers; the server sends `hello` (the verified session) first, then `packet`, `session`, `synced` and `error`; or `reset` after its `hello`, and closes the socket | | `GET /token` | `{ token, expiresAt }`: a short-lived sync token carrying the verified session (servers with `tokens`) | With inline sequencing (the default for HTTP servers), bootstraps, pulls, loads and queries first order pending changes, so a server without a background process still answers from current data. ### Sync barriers A client that must see everything the server committed before some moment (`$sync()`, the sync after `$action`) sends a request that **starts after that moment**: a pull over HTTP, or on a live socket a barrier, `{ t: "sync", id }`. The server answers `{ t: "synced", id }` once the transactions the socket sent before the barrier are applied (their confirmations or rejections are sent first), pending changes are ordered, and every log entry up to the head at that point is delivered on this socket. When the socket closes before `synced`, the client pulls over HTTP instead. ### Starting over A `syncId` is an opaque log position (the entry's number and a random nonce, such as `"42-k3J9xq0a"`, or `"0"` before the first entry); clients send it back unchanged. The server catches a client up from its `since` through the log. It can't when `since` is ahead of the log's head, when the log no longer holds that entry with the same nonce (the database was restored from a backup and wrote other entries since), or when `since` is older than the oldest entry it keeps (`retention.log` pruned the entries in between). It then answers a pull with a single `reset` line, and a socket's `hello` with `reset` before closing the socket. The client bootstraps again, replaces the server state of the models it bootstrapped, reloads the loaded parts of the others (taking the server's rows whatever their revisions), then pulls or reconnects from the new `syncId`. The server applies none of the transactions a refused pull or socket carried. The client's unsent and unconfirmed transactions stay in the outbox and are sent again from the new position. ### Resent transactions A client sends each transaction until it is confirmed or rejected, so the server may receive one it already applied (its answer was lost). It keeps the id of each applied transaction, `(clientId, clientTransactionId)`, for `retention.transactions`, and confirms a resend without applying it again. Each transaction also carries a `base`: the `syncId` the client had when it first tried to send it (stored before it goes out, and forgotten again when the server answers that request with `reset`). The server applies a transaction at or after its base; when it prunes ids, it moves a horizon past the highest head at which a pruned id was applied. A transaction whose id is gone and whose base is below the horizon may have been applied, so the server refuses it with `Stale` instead of applying it twice. In practice that is a write the client kept trying to send, unconfirmed, for longer than `retention.transactions` (attempts while offline count): it is rejected and reported like any other, never applied twice and never dropped silently. ### Sessions **Auth:** HTTP requests send `Authorization: Bearer `. Browsers send `?token=` on the WebSocket, because they can't set WebSocket headers; native clients send the header there too. The server reads `?token=` on WebSocket upgrades only. POST bodies are `Content-Type: application/json` (415 otherwise). Cookies work for same-origin HTTP and same-origin WebSockets; a WebSocket from another origin needs a sync token or an origin that `cors` allows (403 otherwise). The server derives the session from these credentials only, and reports it in every `meta` and in the WebSocket `hello`: - `viewer`: `{ model, id }` for a row of the viewer model, or `null` for anonymous sessions; - `claims`: the names of the claims granted to the session, sorted; - `readOnly`: the server refuses the session's writes. Anonymous sessions are always read-only. Clients never send their viewer. Stored local data belongs to the viewer it was stored for, and a client that sees another viewer deletes it. A client refuses writes locally while its session is read-only. A **claim** grants the session a global group, `claim:|*`; a session's groups are the groups its rules give it plus those of its claims, computed again on every request. A **sync token** (`GET /token`) is an HS256 JWT with audience `clientdb-sync` carrying the whole session: `sub` (absent for anonymous sessions), `tenant`, `claims`, `readOnly`, `iat` and `exp`. A live WebSocket checks its session again while open. Opened with a sync token, the client sends `{ t: "token", token }` with a new token before the current one expires, and the server takes its session; a token that expires without renewal closes the socket. Opened otherwise, the server asks the app for the session again with the upgrade request, once per token lifetime (default 5 minutes). When the claims or the read-only flag changed, the server sends `{ t: "session", viewer, claims, readOnly }`, then a `packet` with the group changes and the rows of granted groups. When the session ended, belongs to another viewer or its token expired, the server sends `{ t: "error", code: "Unauthorized" }` and closes the socket with code 4401. ### Rejections A rejected transaction comes back in `rejected` as `{ clientTransactionId, code, message }`, and its changes are undone on the client. | Code | Meaning | |---|---| | `Forbidden` | a rule refused a write. The message names the branches that failed; for an update, also the fields it refused (`todo.update isPrivate (author: no, admin: no)`, or `(not in any update group)`) | | `ReadOnly` | the session is read-only (a `readOnly` route, a read-only session, or anonymous): its transactions are refused before anything is read or written, on `/push`, `/pull` and the WebSocket alike | | `AccessLost` | the client lost a row the transaction wrote before sending it (issued on the client; the whole transaction is refused) | | `Conflict` | a created row already exists, or rows still reference a row being deleted through a `restrict` relation | | `Validation` | malformed operations, unknown fields, values of the wrong type, generated fields | | `SchemaOutdated` | the transaction was written against another schema version | | `NotFound` | the row the operation names doesn't exist, or the viewer can't read it (refused alike, so rejections never reveal hidden rows) | | `Stale` | the server may have applied the transaction already and no longer keeps its id (see [Resent transactions](#resent-transactions)); it is not applied again | ### Messages ```ts // What a client sends, inside { clientId, clientTransactionId, operations } type Operation = | { type: "create"; model: string; id: string; data: RowData } | { type: "update"; model: string; id: string; data: RowData } | { type: "delete"; model: string; id: string } | { type: "archive"; model: string; id: string; archivedAt: number; archivedBy: string | null } | { type: "unarchive"; model: string; id: string } | { type: "restore"; rows: { model: string; data: RowData }[] }; // undo of a delete // What the server sends type SyncAction = | { type: "upsert"; model: string; id: string; revision: number; row: unknown[]; groups?: string[]; fieldGroups?: FieldGroups } | { type: "delete"; model: string; id: string; revision: number; moved?: boolean } | { type: "invalidate"; model: string } | { type: "groups"; add: string[]; remove: string[] }; type FieldGroups = Record; // restricted field → the viewer's groups that read it interface SyncPacket { syncId: string | null; actions: SyncAction[]; covered?: LoadKey[]; // load keys the packet delivers completely confirmed?: string[]; rejected?: { clientTransactionId: string; code: RejectionCode; message: string }[]; } interface LoadKey { model: string; field: string | null; // null: the whole model key: unknown; } // Resume point: the WebSocket hello, and the base of a pull request interface Hello { protocol: number; clientId: string; since: string | null; // last applied sync id; null needs a bootstrap knownGroups: string[]; clientIds?: string[]; // other tabs' client ids this connection carries } interface PullRequest extends Hello { since: string; transactions?: WireTransaction[]; // pushed before pulling pending?: string[]; // transaction ids the client awaits; applied ones are confirmed } ``` ### What clients rely on - `syncId` values increase in commit order, and log entries are gap-free. - **At most once:** each transaction applies at most once per `(clientId, clientTransactionId)`; resends are confirmed without effect while the server keeps the id, and refused as `Stale` once it pruned an id they may have used (see [Resent transactions](#resent-transactions)). - A client's own transactions come back in `confirmed` or `rejected`, in the packet that contains (or follows) their effects. - **Upserts always carry the full row** as the viewer may read it. `groups` lists the viewer-visible groups of the row; `fieldGroups` the restricted fields the viewer reads, with their groups. - **Restricted fields follow access.** A row may arrive again with the same revision when a newly granted group reveals a restricted field; the client replaces the row's values and `fieldGroups`. When a `groups` action removes every group through which the viewer reads a restricted field, the client hides the field and keeps the row. An update that changes a restricted field the viewer can't read is refused (`Forbidden`); creates may set them. - **Deletes:** `moved: true` means the row left the viewer's groups. Without it, the row was deleted on the server, and the rows that cascade from it with it. - `groups` actions change the session's groups; the rows of newly granted groups follow in the same response or packet, with their eager-relation cascade. After a `groups` action, the client treats what it learned under the old groups as unverified: lazy loads read as incomplete and load again, and answered server queries are asked again. - `invalidate` asks the client to re-fetch a model through `/partial` without `field`. ### Load keys and eager-relation cascades A **load key** `{ model, field, key }` names every row of `model` with `field = key` the viewer may read; `field: null` names the whole model. A model's load keys are `id`, its unique fields and its foreign keys (`loadKeys` in the schema IR). Whenever a load delivers a row (a requested load, a whole-model load, or an eager row of a bootstrap), the server also delivers the row's children through `eager: true` relations, and theirs in turn. The cascade goes down only; the rows a cascaded child points at through other relations come along as single rows; it stops at a model already on its path and at a bootstrap's eager models; and it delivers at most `cascadeRowLimit` rows per response (default 5,000). `covered` lists the load keys the response holds completely; parents a cut cascade went through are left out, and the client loads them when read. A client holds the rows of eager models wholly, and of lazy models only those it loaded. An upsert for a row of a lazy model it doesn't hold is kept only when a complete load matches it; otherwise the client ignores it, so live updates don't pull unrequested rows onto the device. Rows it holds keep updating, and deletes always apply. ### Server queries `POST /query` answers one page of rows matching a predicate, in order: ```json { "model": "todo", "where": [{ "field": "title", "op": "contains", "value": "launch", "mode": "insensitive" }], "orderBy": ["createdAt", "desc"], "limit": 50, "after": null } ``` - `where` conditions must all hold. Operators: `is` (null: the field is null), `in`, `gt`, `gte`, `lt`, `lte`, and on text fields `contains`, `startsWith`, `endsWith`, matched literally. `mode: "insensitive"` (text operators only) compares lowercased. Booleans take `is` and `in`; JSON fields nothing. - `orderBy` is `[field, "asc" | "desc"]` or null; ties, and queries without it, are ordered by `id`. - `limit` is at most the model's `query.maxLimit`; `after` is the previous page's `cursor`. - The model's `query` rules list the fields and operators `where` may use. Restricted fields can't be listed. Results are limited to rows the viewer may read. The answer is a `LoadResult` plus `ids` (the page's rows in order) and `cursor` (`{ value, id }` while more rows match, else null). The client applies it like any load and cuts the query's result at `cursor`, so rows the server hasn't sent yet never show between pages. ## Replica semantics The replica is the state machine on the device that every client implements. It is pure: no IO, clocks, randomness or reactivity. Shells feed it local transactions and server packets and apply the change sets it returns. Each known row has a `base` (the last server-confirmed row), a `revision`, its `groups`, the pending `transactions` that touch it, and an optional `draft`. The visible row is the base with pending effects replayed, then the draft: ```text replay(row, withDraft): exists = base != null; data = copy(base ?? data) for tx in row.transactions, for effect of tx on row (in order): create(d) → exists = true; data = copy(d) delete → exists = false set(f→v) → if exists: data[f] = v if withDraft and draft and exists: apply draft return (exists, data) ``` Key rules from `spec/replica.md`: - **`expand`** turns each operation into row effects and undo steps. A delete visits cascading children recursively, sets `setNull` references to null, and fails on `restrict` references. - **Server input:** an upsert applies only if its `revision` is newer; a real delete records a tombstone and removes cascading children; a `moved` delete just drops the base, and keeps older copies of the row (an answer computed before the move) out; removed groups remove rows whose groups no longer overlap, rejecting their unsent transactions with `AccessLost`. - **Undo** builds inverse operations from the recorded steps, skipping fields whose current value isn't what the transaction wrote, and reports them. - **Reload** re-ingests stored rows, then re-commits each outbox transaction and expands it again against the loaded rows. ## Conformance - An implementation conforms when it reproduces every vector's observations. The TypeScript runner is `checkVector` in `@clientdb/core`; Swift runs the same files. - The server is held to the same `expand` rules: its test suite replays the vectors' local commits as system writes against Postgres and compares the resulting rows. - CI regenerates the vectors (`yarn spec:generate`) and fails if they differ from the committed files, so a change in behavior shows up as a vector diff in review. ## Writing another client 1. Export the schema IR with `exportSchema(schema)`. 2. Implement the replica from `spec/replica.md` and run every vector in `spec/vectors/`. 3. Implement the shells: filling in new rows (defaults, generated fields), the sync driver for the endpoints above, storage, and your platform's reactivity.