Skip to content
clientdb

Search the docs

Find a page or section

Guides

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.

Create

TypeScript
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 enforces authorId: $.viewer.id, pass it yourself, as above.

Update

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

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

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

The transaction handle

TypeScript
import type { TransactionRejection } from "@clientdb/client";

interface TransactionHandle {
  readonly id: string;
  readonly status: "pending" | "sent" | "confirmed" | "rejected";
  readonly sent: Promise<void>;
  readonly confirmed: Promise<void>; // 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.

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

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 (
    <button
      onClick={async () => {
        await db.$action(() => {
          return inviteTeammate(projectId, email);
        });
        // the new member is in db.member now
      }}
    >
      Invite
    </button>
  );
}

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:

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:

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:

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.