Skip to content
clientdb

Search the docs

Find a page or section

Guides

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.

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.

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

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.

CodeMeaning
Forbiddena 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)
ReadOnlythe session is read-only: the route says readOnly: true, session() returned it, or the session is anonymous
Validationunknown field or model, a missing required field, a validate() error, a generated field or a changed primary-key field
Conflictcreate with an existing id, or a delete restricted by references
NotFoundupdate or delete of a row that doesn't exist, or that the viewer can't read
AccessLostthe 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
SchemaOutdatedthe 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 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).