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 forinsertandrestore, so a new row's id isdb.insert(…).value.id;undefinedfor 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);
<script setup lang="ts">import { useDb } from "jazz-tools/vue";const db = useDb();// Query composables return the same handle, so a component that reads and writes needs one:// const { data: todos, db } = useAll(app.todos);</script>
<script lang="ts">import { getDb } from 'jazz-tools/svelte';const db = getDb();// Query subscriptions carry the same handle, so a component that reads and writes needs one:// const todos = new QuerySubscription(app.todos);// todos.db.insert(app.todos, { title: 'Buy milk', done: false });</script>
import { useDb } from "jazz-tools/solid";export function GetDbExample() {const db = useDb();// Query hooks return the same handle, so a component that reads and writes needs one hook:// const todos = useAll(app.todos);// todos.db.insert(app.todos, { title: "Buy milk", done: false });void db;return null;}
import { createJazzClient } from "jazz-tools/client";const session = await createJazzClient({ serverUrl: "/jazz", env: "dev", initial: "device" });const db = session.db;
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);}
export const writeTodoCrud = Effect.fn("writeTodoCrud")(function* (todoId: string) {const jazz = yield* Jazz;yield* jazz.insert(app.todos, {title: "Write docs",done: false,owner_id: EXAMPLE_OWNER_ID,projectId: EXAMPLE_PROJECT_ID,});yield* jazz.update(app.todos, todoId, { done: true });yield* jazz.delete(app.todos, todoId);});
pub async fn write_todo_crud(jazz: &Jazz, todo_id: ObjectId) -> jazz_app::Result<()> {jazz.insert(NewTodo {owner_id: Some(ObjectId::from_uuid(EXAMPLE_OWNER_ID)),project_id: Some(ObjectId::from_uuid(EXAMPLE_PROJECT_ID)),..NewTodo::new("Write docs", false)}).await?;jazz.update(todo_id,TodoUpdate {done: Some(true),..Default::default()},).await?;jazz.delete::<Todo>(todo_id).await}
public func writeTodoCrud(_ jazz: Jazz.Client, todoId: Jazz.ID) async throws {try await jazz.insert(JazzApp.NewTodo(title: "Write docs", done: false, ownerId: exampleOwnerId, projectId: exampleProjectId))try await jazz.update(todoId, JazzApp.TodoPatch(done: .set(true)))try await jazz.delete(JazzApp.Todo.self, id: todoId)}
suspend fun writeTodoCrud(jazz: Jazz, todoId: String) {jazz.insert(Todos,NewTodo(title = "Write docs", done = false, owner_id = EXAMPLE_OWNER_ID, projectId = EXAMPLE_PROJECT_ID),)jazz.update(Todos, todoId) { done(true) }jazz.delete(Todos, todoId)}
func WriteTodoCrud(ctx context.Context, db *jazz.DB, todoID, ownerID, projectID string) error {// Nullable columns are pointers: nil leaves them null.if _, err := jazzapp.Todos.Insert(ctx, db, jazzapp.NewTodo{Title: "Write docs",Done: false,OwnerID: &ownerID,ProjectID: &projectID,}); err != nil {return err}// A patch changes only the fields it sets.if err := jazzapp.Todos.Update(ctx, db, todoID, jazzapp.TodoPatch{Done: jazz.Set(true)}); err != nil {return err}return jazzapp.Todos.Delete(ctx, db, 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" });}
export const upsertTodo = Effect.fn("upsertTodo")(function* (importedTodoId: string) {const jazz = yield* Jazz;yield* jazz.upsert(app.todos,importedTodoId,{ title: "Imported task", done: false },{ wait: "global" },);});
pub async fn upsert_todo(jazz: &Jazz, imported_todo_id: ObjectId) -> jazz_app::Result<Todo> {// A durable handle's writes return once that tier has them.jazz.durable(DurabilityTier::GlobalServer).upsert(imported_todo_id, NewTodo::new("Imported task", false)).await}
public func upsertTodo(_ jazz: Jazz.Client, importedTodoId: Jazz.ID) async throws {try await jazz.upsert(importedTodoId, JazzApp.NewTodo(title: "Imported task", done: false))try await jazz.waitForSync(.global)}
suspend fun upsertTodo(jazz: Jazz, importedTodoId: String) {jazz.upsert(Todos, importedTodoId, NewTodo(title = "Imported task", done = false))// Wait until the sync server has it.jazz.waitForSync(WriteTier.Global)}
func UpsertTodo(ctx context.Context, db *jazz.DB, importedTodoID string) (jazzapp.Todo, error) {return jazzapp.Todos.Upsert(ctx, db, importedTodoID, jazzapp.NewTodo{Title: "Imported task",Done: false,}, jazz.WaitFor(jazz.WriteGlobal))}
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;}
export const restoreDeletedTodo = Effect.fn("restoreDeletedTodo")(function* (todoId: string) {const jazz = yield* Jazz;yield* jazz.delete(app.todos, todoId);const deletedTodo = yield* jazz.one(app.todos.where({ id: todoId }).includeDeleted());if (Option.isNone(deletedTodo)) return yield* new TodoNotFound({ id: todoId });return yield* jazz.restore(app.todos, todoId, {title: "Restored task",done: false,owner_id: EXAMPLE_OWNER_ID,projectId: EXAMPLE_PROJECT_ID,});});
pub async fn restore_deleted_todo(jazz: &Jazz, todo_id: ObjectId) -> jazz_app::Result<Todo> {jazz.delete::<Todo>(todo_id).await?;// `include_deleted` reads deleted rows too.let deleted = jazz.one(todos::query().id(todo_id).include_deleted()).await?;if deleted.is_none() {return Err(jazz_app::Error::NotFound {table: "todos",id: todo_id.to_string(),});}// A restore replaces the whole row, so it takes a full `NewTodo`.jazz.restore_with(todo_id,NewTodo {owner_id: Some(ObjectId::from_uuid(EXAMPLE_OWNER_ID)),project_id: Some(ObjectId::from_uuid(EXAMPLE_PROJECT_ID)),..NewTodo::new("Restored task", false)},).await}
public func restoreDeletedTodo(_ jazz: Jazz.Client, todoId: Jazz.ID) async throws -> JazzApp.Todo {let todos = JazzApp.todos.selftry await jazz.delete(JazzApp.Todo.self, id: todoId)guard try await jazz.one(todos.query().where(todos.id.eq(todoId)).includeDeleted()) != nilelse { throw TodoNotFound(id: todoId) }return try await jazz.restore(todoId,as: JazzApp.NewTodo(title: "Restored task", done: false, ownerId: exampleOwnerId,projectId: exampleProjectId))}
suspend fun restoreDeletedTodo(jazz: Jazz, todoId: String): Todo {jazz.delete(Todos, todoId)checkNotNull(jazz.one(Todos.where(Todos.id eq todoId).includeDeleted())) { "Deleted todo not found" }// With a row as its new content; without one, it comes back as it was.return jazz.restore(Todos,todoId,NewTodo(title = "Restored task", done = false, owner_id = EXAMPLE_OWNER_ID, projectId = EXAMPLE_PROJECT_ID),)}
func RestoreDeletedTodo(ctx context.Context, db *jazz.DB, todoID, ownerID, projectID string) (jazzapp.Todo, error) {if err := jazzapp.Todos.Delete(ctx, db, todoID); err != nil {return jazzapp.Todo{}, err}deleted, err := jazz.IncludeDeleted(jazzapp.Todos.Query().Where(jazzapp.Todos.ID.Eq(todoID))).One(ctx, db)if err != nil {return jazzapp.Todo{}, err}if deleted == nil {return jazzapp.Todo{}, errors.New("deleted todo not found")}// Restores it with these values.return jazz.Restore[jazzapp.Todo](ctx, db, "todos", todoID, jazzapp.NewTodo{Title: "Restored task",Done: false,OwnerID: &ownerID,ProjectID: &projectID,})}
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 FKdb.update(app.todos, todoId, { description: undefined }); // leaves the field unchanged}
export const clearNullableTodoFields = Effect.fn("clearNullableTodoFields")(function* (todoId: string,) {const jazz = yield* Jazz;yield* jazz.update(app.todos, todoId, { owner_id: null }); // clears the nullable FKyield* jazz.update(app.todos, todoId, { description: undefined }); // leaves the field unchanged});
pub async fn clear_nullable_todo_fields(jazz: &Jazz, todo_id: ObjectId) -> jazz_app::Result<()> {jazz.update(todo_id,TodoUpdate {// `Some(None)` sets a nullable column to null.owner_id: Some(None),// `None` leaves a column unchanged.description: None,..Default::default()},).await}
public func clearTodoOwner(_ jazz: Jazz.Client, todoId: Jazz.ID) async throws {// `ownerId` is column `owner_id`. `.set(nil)` stores null; fields left// out (`.unchanged`) keep their value, so `description` stays as it is.try await jazz.update(todoId, JazzApp.TodoPatch(ownerId: .set(nil)))}
suspend fun clearTodoOwner(jazz: Jazz, todoId: String) {// Setting a nullable column to null clears it; columns you don't set// (here `description`) are left unchanged.jazz.update(Todos, todoId) { owner_id(null) }}
func ClearTodoOwner(ctx context.Context, db *jazz.DB, todoID string) error {// A nullable column's patch field holds a pointer: Set(nil) clears it.// Description isn't set, so it stays unchanged.return jazzapp.Todos.Update(ctx, db, todoID, jazzapp.TodoPatch{OwnerID: jazz.Set[*string](nil),})}
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 coordinatessplices: [{ 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 endsplices: [{ 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.tsimport { 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:
| Tier | Resolves when |
|---|---|
local | Saved by the local persistence driver |
global | Authorized 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.
Authorized and durably accepted by Core.
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" });}
export const writeTodoWithDurabilityTiers = Effect.gen(function* () {const jazz = yield* Jazz;const { id } = yield* jazz.insert(app.todos,{title: "Write docs with durability tier",done: false,owner_id: EXAMPLE_OWNER_ID,projectId: EXAMPLE_PROJECT_ID,},{ wait: "global" },);yield* jazz.update(app.todos, id, { done: true }, { wait: "global" });yield* jazz.delete(app.todos, id, { wait: "global" });});
pub async fn write_todo_with_durability_tiers(jazz: &Jazz) -> jazz_app::Result<()> {// A durable handle's writes return once the server accepted them, and// fail if it refused them.let global = jazz.durable(DurabilityTier::GlobalServer);let todo = global.insert(NewTodo {owner_id: Some(ObjectId::from_uuid(EXAMPLE_OWNER_ID)),project_id: Some(ObjectId::from_uuid(EXAMPLE_PROJECT_ID)),..NewTodo::new("Write docs with durability tier", false)}).await?;global.update(todo.id,TodoUpdate {done: Some(true),..Default::default()},).await?;global.delete::<Todo>(todo.id).await}
public func writeTodoWithDurabilityTiers(_ jazz: Jazz.Client) async throws {// Each call returns once the server accepted the write (and its// permissions did).let todo = try await jazz.insert(JazzApp.NewTodo(title: "Write docs with durability tier", done: false, ownerId: exampleOwnerId,projectId: exampleProjectId),tier: .global)try await jazz.update(todo.id, JazzApp.TodoPatch(done: .set(true)), tier: .global)try await jazz.delete(todo, tier: .global)}
// Each call returns once the sync server accepted the write.suspend fun writeTodoWithDurabilityTiers(jazz: Jazz) {val todo = jazz.insert(Todos,NewTodo(title = "Write docs with durability tier",done = false,owner_id = EXAMPLE_OWNER_ID,projectId = EXAMPLE_PROJECT_ID,),tier = WriteTier.Global,)jazz.update(Todos, todo.id, tier = WriteTier.Global) { done(true) }jazz.delete(Todos, todo.id, tier = WriteTier.Global)}
func WriteTodoDurably(ctx context.Context, db *jazz.DB, ownerID, projectID string) error {// Each write returns once the sync server has it.durable := jazz.WaitFor(jazz.WriteGlobal)todo, err := jazzapp.Todos.Insert(ctx, db, jazzapp.NewTodo{Title: "Write docs with durability tier",Done: false,OwnerID: &ownerID,ProjectID: &projectID,}, durable)if err != nil {return err}if err := jazzapp.Todos.Update(ctx, db, todo.ID, jazzapp.TodoPatch{Done: jazz.Set(true)}, durable); err != nil {return err}return jazzapp.Todos.Delete(ctx, db, todo.ID, durable)}
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:
| State | Meaning |
|---|---|
local-only | No server is configured, so nothing is uploaded |
connecting | Connecting for the first time, or reconnecting after a short drop |
connected | Connected to the server |
offline | Not 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 nullconst 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: withPersistedWriteRejectedErroron the local-first client, and with aThinRemoteError(codeWriteRejected) 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;}}
export const insertTodoAndWait = Effect.gen(function* () {const jazz = yield* Jazz;const row = yield* jazz.insert(app.todos,{title: "Ship review fixes",done: false,owner_id: EXAMPLE_OWNER_ID,projectId: EXAMPLE_PROJECT_ID,},{ wait: "global" },);yield* Effect.log(row.id);}).pipe(// The server rejected the write; it has already been undone locally.Effect.catchTag("JazzWriteRejected", (rejected) =>Effect.logError(rejected.code, rejected.reason),),);
pub async fn insert_todo_and_wait(jazz: &Jazz) -> jazz_app::Result<Option<Todo>> {// A durable write returns once the server accepted it, and fails with// its verdict if it refused it.let inserted = jazz.durable(DurabilityTier::GlobalServer).insert(NewTodo {owner_id: Some(ObjectId::from_uuid(EXAMPLE_OWNER_ID)),project_id: Some(ObjectId::from_uuid(EXAMPLE_PROJECT_ID)),..NewTodo::new("Ship review fixes", false)}).await;match inserted {Ok(todo) => Ok(Some(todo)),// `code` is TypeScript's: `permission_denied`, `write_rejected`, …Err(jazz_app::Error::WriteRejected { code, reason, .. }) => {eprintln!("{code}: {reason}");Ok(None)}Err(error) => Err(error),}}
public func insertTodoAndWait(_ jazz: Jazz.Client) async throws {do {let todo = try await jazz.insert(JazzApp.NewTodo(title: "Ship review fixes", done: false, ownerId: exampleOwnerId,projectId: exampleProjectId),tier: .global)print(todo.id)} catch JazzError.permissionDenied(let reason) {// The server rejected the write.print("permissionDenied", reason)}}
// A write at WriteTier.Global returns once the server accepted it, and throws// if the server rejects it. JazzException has no code field: its subtype says// what kind of rejection it is (Permission when permissions deny it, Refused// when it's invalid), and its message gives the reason.suspend fun insertTodoAndWait(jazz: Jazz): Todo? =try {jazz.insert(Todos,NewTodo(title = "Ship review fixes", done = false, owner_id = EXAMPLE_OWNER_ID, projectId = EXAMPLE_PROJECT_ID),tier = WriteTier.Global,)} catch (e: JazzException.Permission) {System.err.println("permission denied: ${e.message}")null} catch (e: JazzException.Refused) {System.err.println("refused: ${e.message}")null}
func InsertTodoAndWait(ctx context.Context, db *jazz.DB, ownerID, projectID string) (string, error) {todo, err := jazzapp.Todos.Insert(ctx, db, jazzapp.NewTodo{Title: "Ship review fixes",Done: false,OwnerID: &ownerID,ProjectID: &projectID,}, jazz.WaitFor(jazz.WriteGlobal))var rejected *jazz.Errorif errors.As(err, &rejected) {// The server refused it: its kind (e.g. permission) and reason.return "", fmt.Errorf("rejected (%s): %s", rejected.Kind, rejected.Message)}return todo.ID, err}
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);});}
// Rejections of writes nobody waited for. Fork this for the app's lifetime.export const logMutationErrors = Effect.gen(function* () {const jazz = yield* Jazz;yield* jazz.mutationErrors.pipe(Stream.runForEach((event) => Effect.logError("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.