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.
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.
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
undoLimiton the client to change it.
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.confirmedrejects with aTransactionError;- the client's
onTransactionErroroption and everydb.$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:
"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 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).