Writing Data

Learn how to insert, update and delete rows, show sync status and handle write errors.

How writes work

Writes are methods on the Db handle: insert, upsert, update, delete and restore. Each call commits as its own transaction, which the server checks against your declarative permissions and accepts or rejects as a whole. To make several reads and writes commit together, group them in a transaction.

insert and restore return a WriteResult; update, upsert and delete return a WriteHandle. Both have:

  • value — The written result: the row for insert and restore, so a new row's id is db.insert(…).value.id; undefined for the others. Inside a transaction, tx.insert(…) returns the staged row itself.
  • txId — A promise for the committed transaction ID, the durable identity of this write.
  • wait(...) — A method that waits until the write is confirmed at a durability tier, for example accepted by the server.

Writes made through an open transaction are not individually waitable. Wait on the result returned by the transaction or its commit() call instead.

When a write shows up depends on the client. A thin client shows it after the server answers. A local-first client applies it to its local database first, so it shows at once, before the server has seen it. Write durability tiers covers what that means when you wait.

Getting a Db handle

Every framework provides a hook to access the database handle, and query hooks return it too. In plain TypeScript, use session.db from createJazzClient.

import { useDb } from "jazz-tools/react";
​
const db = useDb();
​
// Query hooks return the same handle, so a component that reads and writes needs one hook:
// const { data: todos, db } = useAll(app.todos);

Insert, update, delete

Mutations are methods on the database handle. All three take a table as their first argument.

export async function writeTodoCrud(db: Db, todoId: string) {
db.insert(app.todos, {
title: "Write docs",
done: false,
owner_id: EXAMPLE_OWNER_ID,
projectId: EXAMPLE_PROJECT_ID,
});
db.update(app.todos, todoId, { done: true });
db.delete(app.todos, todoId);
}

Upsert with a known ID

Use upsert(...) when your app already knows the row ID and wants to create that row if it does not exist, or update it if it does. Like insert, update, and delete, it returns a MutationResult<void> that can be awaited for durability.

export async function upsertTodo(db: Db, importedTodoId: string) {
const write = db.upsert(app.todos, importedTodoId, {
title: "Imported task",
done: false,
});
​
await write.wait({ tier: "global" });
}

Restore a deleted row

Trying to insert, update or delete an already deleted row will fail. Use restore(...) to make a soft-deleted row visible again. restore requires providing new data for the restored row (missing fields will use schema defaults, if they exist). Deleted rows are omitted from queries by default. Add includeDeleted() when you need to find a row before restoring it.

restore is only for a deleted row: on a live one it fails with row not deleted. When you don't know which it is, check $deletedAt, which a query with includeDeleted() can select:

const existing = await db.one(app.todos.where({ id }).includeDeleted().select("$deletedAt"));
if (existing?.$deletedAt) db.restore(app.todos, id, values);
else db.update(app.todos, id, values);
export async function restoreDeletedTodo(db: Db, todoId: string) {
db.delete(app.todos, todoId);
​
const deletedTodo = await db.one(app.todos.where({ id: todoId }).includeDeleted());
if (!deletedTodo) throw new Error("Deleted todo not found");
​
const { value: restored } = db.restore(app.todos, todoId, {
title: "Restored task",
done: false,
owner_id: EXAMPLE_OWNER_ID,
projectId: EXAMPLE_PROJECT_ID,
});
​
return restored;
}

Partial updates and nullable fields

update(...) only modifies the keys you pass. Omitted fields are left unchanged; explicitly passing undefined also leaves a field unchanged. To clear a nullable column in TypeScript, pass null. Required fields cannot be set to null.

export function clearNullableTodoFields(db: Db, todoId: string) {
db.update(app.todos, todoId, { owner_id: null }); // clears the nullable FK
db.update(app.todos, todoId, { description: undefined }); // leaves the field unchanged
}

Editing a page of a large value

Use update(...) to replace complete primitives and, with its applyDiffs option, edit a selected page of a bytes or string column or set an existing JSON member. Replacements and diffs are one atomic update, but a column must appear in only one of them. Splice coordinates are relative to within, and multiple splices run in order against the result of the previous splice.

db.update(
app.documents,
documentId,
{ title: "Revised document" },
{
applyDiffs: {
bytes: {
within: { from: 1_000_000, to: 2_000_000 },
splices: [{ at: 4, delete: 3, insert: new Uint8Array([1, 2]) }],
},
text: {
within: { from: 4, to: 124 }, // UTF-16 coordinates
splices: [{ at: 3, delete: 1, insert: "revised" }],
},
metadata: {
edits: [{ op: "set", at: "/chapters/0/title", value: "New title" }],
},
},
},
);

For a diff-only update, pass an empty replacement object:

db.update(
app.documents,
documentId,
{},
{
applyDiffs: {
text: {
within: { from: 4, to: 124 },
splices: [{ at: 3, delete: 1, insert: "revised" }],
},
},
},
);

For byte-oriented text, use { fromUtf8, toUtf8 } in within and { atUtf8, deleteUtf8, insert } in each splice. In Rust, text pages and splices count UTF-8 bytes (str indices): jazz.splice(id, column, Page::text(from..to), vec![Splice::text(at, delete, "revised")]), and an offset inside a code point fails with Error::TextOffset. Jazz rejects out-of-range coordinates and text boundaries that split a code point or surrogate pair. This revision does not add a page-staleness/CAS check; keep page coordinates aligned with the value your application last read. update(..., { applyDiffs }) is for existing rows only; inserts and full replacement continue to use the ordinary mutation methods.

applyDiffs also works inside a transaction. Coordinates are relative to the value the transaction sees, including its own earlier writes, so an append after an append in the same transaction lands after both, and every diff commits together with the transaction's other writes:

await db.transaction(async (tx) => {
tx.update(
app.documents,
documentId,
{ editedAt: new Date() },
{
applyDiffs: {
text: {
within: { from: length, to: length }, // an empty page at the end
splices: [{ at: 0, delete: 0, insert: nextTokens }],
},
},
},
);
});

Only the pages a diff touches are rewritten, so streaming many small appends into a long value stays cheap however long it grows.

Uploading and downloading files

Store a file in a bytes column next to its metadata:

schema.ts
import { schema as s } from "jazz-tools";
​
export const schema = s.defineSchema({
files: s.table({
name: s.string(),
type: s.string(),
size: s.int(),
content: s.bytes(),
}),
});

Upload from the browser with insertStreaming, which streams the bytes into the row instead of copying the whole file into memory. It works in the thin and the local-first client, and it goes through /jazz, so the file never passes through a route of your own:

async function upload(file: File) {
const inserted = await db.insertStreaming(app.files, {
name: file.name,
type: file.type,
size: file.size,
content: file.stream(),
});
await inserted.wait({ tier: "global" });
return inserted.value.id;
}

updateStreaming and upsertStreaming replace a file in an existing row the same way.

To download, select the column. For a large file, read it a page at a time with a range (see Partial large values):

const row = await db.one(app.files.where({ id }).select("name", "type", "content"));
const url = URL.createObjectURL(new Blob([new Uint8Array(row!.content)], { type: row!.type }));
​
// Or the first megabyte only:
const head = await db.one(app.files.where({ id }).select({ content: { from: 0, to: 1_048_576 } }));

Transactions

Use a transaction when several reads and writes must share one commit. Use a mergeable transaction for most work. Use a serializable transaction only when the authority must check the whole operation against one stable view of the data.

See Transactions for examples, error handling and the differences between commit and authority acceptance.

Write durability tiers

A write can be confirmed at two points: when the client has saved it, and when the server has accepted it. For ordinary mutations and mergeable transactions, wait({ tier }) controls which confirmation the caller waits for:

TierResolves when
localSaved by the local persistence driver
globalAuthorized and durably accepted by Core

Each write picks a fresh colour. Choose how durable it must be before it's confirmed — it lands on this device at once, then syncs to Core and then to the other device whenever the network is available; the promise resolves once it reaches the tier you picked. Turn on aeroplane mode to watch writes queue on the device and flush when you reconnect. Local confirms after local persistence, even offline.

Wait for

Authorized and durably accepted by Core.

#146aff
StatusReady
Local-onlyall synced
Core
accepts writes
Other device
receives updates

Offline, only local can resolve. A global wait stays pending until the device reconnects and Core accepts or rejects the queued write, however long the outage lasts. Both choices apply the initial mutation locally and upload it when connected.

A global wait fails early only when the client stops trying to reach Core: a protocol error, a closed client, or a credential the server refuses that nothing renews. Only an account context's refresh cycle and a device account's token the Db mints itself count as renewing a credential, so their waits outlast an expired token. With a static token or a backend secret, a refused credential ends the wait. To bound how long you wait, pass timeoutMs. The wait then rejects with a WriteWaitTimeoutError (code: "timeout"), but the write stays queued and may still be accepted, so do not retry it:

try {
await db.insert(app.todos, { title: "Buy milk" }).wait({ tier: "global", timeoutMs: 5_000 });
} catch (error) {
if (error instanceof WriteWaitTimeoutError) showPendingBadge();
else throw error;
}
export async function writeTodoWithDurabilityTiers(db: Db) {
const { id } = await db
.insert(app.todos, {
title: "Write docs with durability tier",
done: false,
owner_id: EXAMPLE_OWNER_ID,
projectId: EXAMPLE_PROJECT_ID,
})
.wait({ tier: "global" });
​
await db.update(app.todos, id, { done: true }).wait({ tier: "global" });
await db.delete(app.todos, id).wait({ tier: "global" });
}

See Durability Tiers for the full reference, including read durability, data flow between tiers, and consistency semantics.

Need to clear local data during development? See Resetting browser storage.

Showing sync status

To show whether the user's changes have reached the server, read the Db's sync status. It combines the upstream connection with the number of transactions the server has not accepted or rejected yet:

const status = db.getSyncStatus();
// {
// link: { state: "offline", reason: "network", retrying: true },
// pendingUploads: 3,
// synced: false,
// }
​
const unsubscribe = db.onSyncStatusChange((status) => renderBadge(status));

link.state is one of:

StateMeaning
local-onlyNo server is configured, so nothing is uploaded
connectingConnecting for the first time, or reconnecting after a short drop
connectedConnected to the server
offlineNot connected. reason says why: disconnected after db.disconnect(), network when the server has been unreachable for a while (the client keeps retrying), auth when the server refused the credential, or stopped after a failure that only db.reconnect() retries

offline can also have the reason authority-changed: the server serves a different history than the client's local store, because the server's store was recreated (a deleted dev data directory, a restarted in-memory server, a new environment behind the same URL) or it is another app's server. The client stops syncing with it, keeps its local data and unsynced writes, and fails global waits and db.waitForSync() with an AuthorityChangedError (check with isAuthorityChangedError). Nothing is reset automatically. To sync with the new server, reset the local store: in the browser, await db.deleteClientStorage(); in Node, delete the client's data directory and open it again. Writes that never reached the old server are lost with the store.

In the browser, every tab that syncs through the shared worker sees this too, including a tab opened or reloaded after the refusal: its global waits fail the same way and its sync status shows offline with the reason authority-changed, while local reads and writes keep working.

In the browser, offline can also have the reason held-by-another-tab, with retrying: true. One local store serves one sign-in and one schema at a time, so a tab waits for it when:

  • a guest signs up in one tab while another tab still holds the account's local store as the guest. The signed-up tab waits for that tab to follow the sign-up or close.
  • a deploy changed the app's schema, and a tab of another build has the store open, but Jazz can't tell which build is newer (see below). The tab waits for that one to reload or close.

Meanwhile the waiting tab shows connecting, and it joins once the other tab lets go. If that hasn't happened after 30 seconds (the other tab may be frozen in the background), the link reports held-by-another-tab, and waits fail with a StoreHeldByAnotherTabError (check with isStoreHeldByAnotherTabError), so the app can ask the user to close or reload the other tab. The tab keeps trying and joins as soon as it can. Writes made meanwhile stay in that tab's memory until then, so a reload before it joins loses them.

A new deploy and tabs of the previous build

After a deploy that changes the schema, the newer build takes the local store, and tabs of the previous build reload. Each build knows its schema history (the versions and migrations in jazz.generated.ts), so Jazz can tell which build came later: the one whose history contains the other's.

  • When a tab of the newer build opens, each tab of the older build stops taking writes (new writes, queries and transaction commits throw until it reloads). It makes the writes it already took durable in the local store and lets go of the store. Then it reloads, which loads the newer build. A tab that doesn't let go within 5 seconds (frozen in the background, say) is closed, as a crashed tab would be: the writes it had already handed to the shared worker are kept, and whatever it hadn't sent yet is lost. The newer tab then opens the store with its schema and reads the older rows through its migrations. Writes the older build made but hadn't uploaded yet stay in the store and upload as they are, so keep the previous schema version published until they have.
  • A tab of the older build that opens while the newer one has the store (a stale tab, a page restored from history) reloads too. If it loads the very same build again (a CDN that hasn't caught up, or a rollback to the previous build, which Jazz orders as older), it doesn't reload again in that tab's session: it waits as described above, and joins once the newer build's tabs have gone.
  • Builds Jazz can't order, because neither history contains the other (unrelated builds on one origin) or one ships none, don't take the store from each other: the newer tab waits.

To decide when the old tab reloads (after a "a new version is available" notice, or once a form is saved), pass onNewerBuild to createJazzClient. It gets the reload to call:

const session = await createJazzClient({
// ...
onNewerBuild: (reload) => {
showNotice("A new version of this app is available.", { action: "Reload", onAction: reload });
},
});

Until it calls reload(), the tab keeps showing what it already shows; new writes, queries and commits throw.

A brief drop shows as connecting, not offline, so a status badge doesn't flicker. synced is true when nothing waits for upload and the link is connected (or local-only).

In Node and React Native, pendingUploads includes transactions recovered from local storage after a restart. In the browser, each tab counts only the transactions it committed itself. Transactions recovered after a reload, or written by another tab, are uploaded by the shared worker and are not counted, and db.waitForSync() does not wait for them.

The framework bindings expose the same object: useSyncStatus() in React and React Native (from jazz-tools/react-native, also in Expo apps; the object), in Solid (an accessor) and in Vue (a ref), and syncStatus() in Svelte (a store, read as $status). The Effect layer has a syncStatus stream.

function SyncBadge() {
const { link, pendingUploads, synced } = useSyncStatus();
if (synced) return <span>Saved</span>;
if (link.state === "offline") return <span>Offline, {pendingUploads} changes waiting</span>;
return <span>Saving…</span>;
}

To wait until everything written so far has reached the server, for example before letting the user sign out, use db.waitForSync(). Like a global write wait, it lasts through outages and reconnects, and fails only if the server rejects one of those writes or the client stops trying. Pass timeoutMs to bound it; it then rejects with a WriteWaitTimeoutError and the writes stay queued. In the browser it waits only for the current tab's own writes, as described above, so a write recovered after a reload or made in another tab may still be waiting when it resolves:

await db.waitForSync({ timeoutMs: 10_000 });

Which rows are still waiting

To mark individual rows as not yet saved, such as a message that has not reached the server, ask for the rows a table's pending transactions wrote:

const pending = db.getPendingUploadRows(app.messages); // ["0193…", …] or null
const unsubscribe = db.onPendingUploadRowsChange(app.messages, (ids) => renderMarks(ids));

A row is listed from the moment a transaction that wrote it is committed until the server accepts or rejects that transaction, including transactions recovered from local storage after a restart (with the same browser caveat as pendingUploads). The IDs are sorted, and the listener fires only when the set changes. The result is null while the Db cannot name rows yet, for example while it still runs on a thin startup runtime; treat null as "unknown", not as "nothing pending".

Handling mutation errors

A mutation can fail when you call it or while you wait:

  • If Jazz cannot apply the mutation locally, for example because the input is invalid, the mutation call throws immediately.
  • If a server later rejects the mutation, an active wait(...) call rejects: with PersistedWriteRejectedError on the local-first client, and with a ThinRemoteError (code WriteRejected) on the thin client.
export async function insertTodoAndWait(db: Db) {
const pending = db.insert(app.todos, {
title: "Ship review fixes",
done: false,
owner_id: EXAMPLE_OWNER_ID,
projectId: EXAMPLE_PROJECT_ID,
});
​
console.log(await pending.txId);
​
try {
const row = await pending.wait({ tier: "global" });
console.log(row.id);
} catch (error) {
if (error instanceof PersistedWriteRejectedError) {
console.error(error.code, error.reason);
return;
}
​
throw error;
}
}

Use db.onMutationError(...) as a fallback for rejected mutations without an active wait(...). Its event is not an Error: read event.code and event.reason, not .message. This includes mutations you did not wait for and mutations whose wait finished before a later rejection arrived.

An event with code outcome_unknown is not a rejection: the thin client's connection ended for good before the server answered (after refresh() signed in someone else, disconnect() or close()), and the write may have been applied. Read the row again before you revert or retry it. An ordinary dropped socket doesn't cause this, since the thin client resends unanswered writes when it reconnects.

export function listenForMutationErrors(db: Db) {
return db.onMutationError((event) => {
console.error("DB mutation failed:", event.code, event.reason);
});
}

onMutationError returns an unsubscribe function. Without a listener, Jazz logs the rejection and keeps it so that a listener registered later can receive it.

On a server, jazz.db, jazz.forReqUser() and jazz.withAttribution() from one createJazz share one runtime, but each rejection goes only to the Db that made the write. jazz.db and other backend-wide Dbs, which all write as the backend, share theirs. A per-request handler never sees another user's rejection, even one from another request by the same user, so it can forward what it gets to its requester. Rejections Jazz can't trace to the Db that made them go only to jazz.db: writes made while no listener was registered anywhere, and writes that were still in flight when the process stopped and are settled on restart. Those that arrive before jazz.db has a listener wait for its first one. Jazz keeps up to 256 of them and reports how many it dropped beyond that. A dropped or shut-down Db releases its listeners, so register long-lived listeners on jazz.db: a listener on a per-request Db stops firing once that Db is garbage-collected.