Skip to content
clientdb

Search the docs

Find a page or section

Get started

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: users, projects, project members and todos with comments.

1. The local replica is the UI's source of truth; the server is the authority

This device
Your componentsread and write
instant
The local replicathe rows this user may read
sync, in the background
Your serverchecks every write against your rules
Postgresthe final word

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, 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:

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 <span>{openCount} open</span>;
}

The same goes for single rows and the signed-in user:

TypeScript
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 and 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:

TypeScript
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, Transactions and undo and, for the details, Conflicts and rejections.

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:

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 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:

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: it has a read rule of its own.

See Schema and 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:

loadWhen the rows arriveIn the todo app
"eager"when the app starts; DatabaseProvider shows its fallback until they are thereusers, projects, members, todos
"lazy" (default)the first time something reads them, then they staycomments

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:

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 <Spinner />;
  }
  return comments.map((comment) => {
    return <p key={comment.id}>{comment.body}</p>;
  });
});

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.

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:

TypeScript
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.

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, 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 writeWith clientdb
an API route and a fetch per read and per writeone route handler, and the rules file
a client cache, with query keysthe replica is the cache
a loading spinner per componentreads return data; one fallback while the app first loads
invalidation and refetching after each writeevery query that read a row updates when it changes
optimistic updates, and rolling them back by handevery write is optimistic and rolls back on its own
permission checks repeated in each routeread 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:

TypeScript
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.

Where to go next