Prisma IDB FaviconPrisma IDB

Sync client

Reference for the browser side of sync, the outbox, and the sync worker

Reference for @prisma-idb/sync-extension-idb. To set it up, follow the Sync tutorial.

Opening a sync client

All three functions come from @prisma-idb/sync-extension-idb/client.

FunctionUse it when
createManagedAutoSyncIdbClient(options)Most apps. A shared client with get(), close() and reset(), like createManagedAutoIdbClient.
createAutoMigratingSyncIdbClient(options)You manage the client's lifetime yourself. Migrates, then returns a sync client.
createSyncIdbClient({ contract, dbName })The database is already migrated.

The options are the same as createAutoMigratingIdbClient's, plus trackedModels: an array of model names to record for sync, or "*" for every model, the default. Writes to other models stay local. Tracked models must use keys that are unique across devices, such as uuid() or cuid(). Sync rejects tracked stores with autoincrement() keys. Include idbSyncExtension from @prisma-idb/sync-extension-idb/control in extensions, so the database gets the sync stores, _idb_sync_outbox and _idb_sync_version_meta.

The managed handle exposes managedDb.enums synchronously with the same type and values as db.enums. Reading enum values does not open IndexedDB and works during server rendering, even when no indexedDB global exists. Use await managedDb.get() when you need database operations.

Client members

MemberDescription
db.ormThe same API as a plain client. Writes to tracked models are also recorded for sync.
db.withoutTracking(fn)Runs fn(orm) with writes that aren't recorded, so they never sync.
db.on("outboxwrite", cb)Calls cb after a tracked write commits, with the recorded changes. Returns an unsubscribe function.
db.outbox.hasPending()Returns Promise<boolean>: whether an unsynced, retryable event remains.
db.outbox.pendingCount()Returns Promise<number>: the number of unsynced, retryable events.
db.on("outboxchange", cb)Calls cb with no payload after an append or status update commits. Returns an unsubscribe function.
db.createSyncWorker(opts)Creates a sync worker for this client.
db.rawClientThe underlying plain client. Writes through it aren't recorded.
db.verifyMarker(), db.close()Same as on a plain client.

The outbox

Every tracked write through db.orm also writes an event to the outbox store, in the same transaction. The two commit together or not at all, so no change is ever lost or sent without being saved.

"outboxwrite" fires after commit, once per tracked IndexedDB write call. A single call can report several entries, such as the rows from a bulk scan-write. Nested writes, foreign-key-aware creates and cascading deletes can use several driver calls, so one ORM method can produce several notifications. A rolled-back transaction produces none.

const unsubscribe = db.on("outboxwrite", (entries) => {
  // entries: readonly { modelName, operation, key, payload }[]
});

Use db.outbox.hasPending() for a sync button and db.outbox.pendingCount() for a pending badge. Both include retryable events waiting for backoff. They exclude synced events and permanent rejections (retryable: false). Each call reads committed state from IndexedDB.

db.on("outboxchange", callback) fires after tracked appends, successful pushes, and failed pushes, including requests that throw or time out. It has no payload; read the pending status again in the callback. A bulk write or push-result transaction emits once after commit, even if it changes several events. A tracked db.transaction() also emits once. Rollbacks and reads emit nothing. Low-level markSynced and markFailed calls participate when used inside this client's withTransaction or rawClient.withTransaction. Direct raw writes to the outbox store do not emit notifications. Notifications belong to this client instance.

Use withoutTracking for writes the server shouldn't receive, such as local-only drafts, or a copy of a row that came from the server:

await db.withoutTracking((orm) => orm.user.upsert({ where: { id }, create: user, update: user }));

Conflicts

For each synced record, _idb_sync_version_meta records two things:

  • Whether a local change is waiting to be pushed. While one is, a pull stops at that record, so a local change is never overwritten before it reaches the server.
  • The last changelog id applied to it. A row that is not newer counts as already applied, so a repeated or out-of-order pull can't undo a newer change.

The worker maintains this store; you don't write to it.

The pull cursor

A pull applies its rows in order. A later row can depend on an earlier one, so the pull never skips ahead of a row it could not apply: a write failure or a pending local change stops the pull, and no later row lands before it. The one exception is an invalid row, which the pull consumes without writing it.

Each row ends in one of four ways:

OutcomeMeaningEffect on the pull
appliedThe row was written.Continues. The cursor moves past it.
already-appliedThe record already has a newer or equal change. This happens when a page is replayed after a crash.Continues. The cursor moves past it.
invalidThe record or key fails the client contract. No retry can fix it. It is counted in validationFailed. Local data stays.Continues. The cursor moves past it.
haltThe write failed (for example a full disk) or the record has a pending local change.Stops. Later rows are not applied. The cursor stays before this row.

The pullcompleted event reports halted: true when a pull stopped early. The next pull restarts at the halted row. A row for a model that is not in the client contract is skipped and does not halt the pull.

Applied changes

The pullcompleted event and the applyPull result include changes: PullChange[]. Each entry describes one applied changelog entry. Use this list to invalidate queries for affected models and keys.

FieldMeaning
modelPrisma model name, such as "User", rather than its IndexedDB store name.
keyNative IndexedDB key. Compound keys are arrays in the contract's key-field order. Bytes and DateTime components use Uint8Array and Date values, rather than wire strings. Decimal keys retain the local row's stored spelling.
op"create", "update" or "delete", matching the changelog operation. Revoked ownership (record: null) is reported as "delete".

The list follows page order and can contain the same key more than once. It contains only committed entries: replays, invalid rows, unknown models, the halted row and later rows are excluded. Each event contains only that pull page's changes. An empty page produces an empty list. A delete can cascade to related rows or set their foreign keys to null. Those side effects are not separate changelog entries in this list, so consumers should also invalidate queries for related models.

PullChange is exported from @prisma-idb/sync-extension-idb/client. PullCompletedEvent and ApplyPullResult require the changes field.

Rejected pushes

When the server rejects an event for good (retryable: false), the worker replaces the local row with the server's row from the push result's record. A rejected create is removed, a rejected update is replaced by the server's row, and a rejected delete is restored. The change adds no outbox event.

The rejected event stays in the outbox with retryable: false and its full payload, so the user's write is not lost. Do not delete it.

If the result has no usable record (an older server, or a record that fails the client contract), the local write stays until a pull overwrites it. The pushcompleted event counts these in unreconciled.

Avoid user-chosen natural-key unique constraints on models that clients create offline. Two devices can create the same value, and the server keeps only the first one. Use a surrogate id as the primary key. See ADR 022.

Fetch transport

createSyncFetchHandlers({ pushUrl, pullUrl, fetch?, headers?, credentials? }) returns pushHandler and pullHandler for a worker. Relative URLs require a browser location. Outside a browser, use absolute URLs.

The handlers send storageHash in the push body and pull query, forward cancellation, validate response shapes, and raise ContractMismatchError on HTTP 409. Other non-success statuses throw an ordinary error. Pull replaces the since parameter with the last applied cursor and retains other endpoint parameters. The first pull removes any existing since parameter.

headers accepts HeadersInit. The helper sets the push content type. credentials defaults to "same-origin". Pass a custom fetch function for dynamic authentication, such as refreshing a bearer token.

import { createSyncFetchHandlers } from "@prisma-idb/sync-extension-idb/client";

const worker = db.createSyncWorker(
  createSyncFetchHandlers({
    pushUrl: "/api/sync/push",
    pullUrl: "/api/sync/pull",
  })
);

Sync worker

const worker = db.createSyncWorker({ pushHandler, pullHandler });
worker.on("error", (error) => {
  console.error("Sync failed:", error.message);
});
worker.start();

The worker doesn't start on its own. Each cycle first pushes: it sends batches of outbox events until none is left to send. It then pulls, but only if no retryable event remains in the outbox. This keeps a pull from landing on an edit the server has not seen. A cycle repeats every intervalMs while idle, and backs off after failures.

The worker automatically keeps the newest 100 successfully acknowledged outbox events per database, ordered by createdAt descending and event id descending for ties. It prunes before each cycle's first push, including idle cycles, and after each push-result batch in the same transaction as the results. Unsent and failed events keep their full payload and error, including permanent rejections. Version metadata is preserved. This cleanup applies only to the worker; direct calls to low-level outbox helpers such as markSynced do not prune history.

A failed push, including a request that throws or times out, stays retryable however many times it fails, unless the server says it can never succeed. Events are pushed in order, so an event that is waiting out its backoff holds back the events behind it. After 10 failed tries, pushcompleted carries stalled: { eventId, tries, lastError } for the oldest event. Show it to the user: the outbox is stuck behind that event, and pulls pause until it clears.

OptionDefaultDescription
pushHandlerRequired(events, signal, context) => Promise<PushResult[]>. Sends events to your push endpoint.
pullHandlerRequired(fromChangelogId, signal, context) => Promise<LogWithRecord[]>. Fetches changes after fromChangelogId, which is null on the first pull.
syncOnReconnectfalseSync on online and when the page becomes visible while the worker is started.
batchSize20Outbox events pushed per request.
intervalMs5000Time between cycles while idle.
backoffBaseMs1000Wait after the first failure. Doubles with each failure in a row. Applies to failed cycles and to each outbox event.
backoffMaxMs30000The longest wait, for both.
requestTimeoutMs30000Aborts a handler call through its signal after this long.

Custom handlers receive context.storageHash, the emitted client contract's storage.storageHash. Send it with the request, in the push body or pull query, and forward it to the server's pull and applyPush. If the server answers 409, throw ContractMismatchError (exported from @prisma-idb/sync-extension-idb/client) from the handler. The worker keeps the pull cursor, the queued edits and their payloads. It emits contractmismatch with { during: "push" | "pull" }, sets status to "error", retries with backoff, and does not emit error for that mismatch. Use the event to ask the user to reload. See Contract check.

Method or propertyDescription
start()Starts the loop. Does nothing if it's running.
stop()Returns Promise<void>. Stops notifications and new cycles, then waits for the active cycle to settle.
forceSync(options?)Runs a cycle now. Respects event retry delays unless overrideBackoff is true.
status"idle", "pushing", "pulling", "error" or "stopped".
on(event, cb)Subscribes to "statuschange", "error", "pushcompleted", "pullcompleted" or "contractmismatch". Returns an unsubscribe function.

forceSync(options?: ForceSyncOptions) starts a cycle immediately, skipping the scheduled loop wait. It respects pending events' retry delays by default. Set overrideBackoff: true to bypass those delays for the cycle it starts. ForceSyncOptions is exported from @prisma-idb/sync-extension-idb/client.

await worker.forceSync(); // Respect event retry delays (the default).
await worker.forceSync({ overrideBackoff: false }); // Same behavior.
await worker.forceSync({ overrideBackoff: true }); // Retry pending events now.

Concurrent calls join the active cycle without changing its options or starting another cycle. The override preserves event order, attempt counts and the stalled signal. It does not resend permanent rejections. Another retryable failure ends the push phase, and pulls stay blocked until pending events clear. Later cycles use the configured backoff again.

statuschange receives the same lowercase string as status. The legacy generated worker uses uppercase statuses and a different status object. Use lowercase comparisons when migrating to this package.

The error event receives the thrown Error after status becomes "error". It covers push, pull, timeout, and cursor persistence failures, except contract mismatches, which emit only contractmismatch. Error subclasses, stacks, and causes are preserved. Other thrown values are wrapped in an Error with String(value) as the message and the original value as cause. If string conversion throws, the message is "Sync cycle failed". Listener exceptions are ignored so other subscribers still receive notifications and sync failures keep their original rejection. Each failed cycle emits once, even if concurrent callers share it. A failure that settles after stop() does not emit this event.

forceSync() also sets the error status and emits the appropriate failure event (contractmismatch or error), while its promise rejects with the original thrown value. Handle that rejection when calling it. A successful cycle returns the status to "idle". Per-event server rejections use pushcompleted and the outbox error fields; they do not emit a cycle error unless the cycle throws.

The pull cursor is stored in _idb_sync_meta in the same IndexedDB database as your data. New clients resume from that cursor. A failed cursor write fails the cycle and is retried after the next successful pull. getCursor and setCursor options have been removed.

On sign-out, await worker.stop() before calling your managed client's reset(). The active request may finish or reach requestTimeoutMs; its database writes settle before stop() resolves. The worker emits "stopped" immediately and suppresses subsequent cycle notifications. start() does nothing while stopping. forceSync() does nothing once stopped; call start() to restart the loop.

await worker.stop();
await db.reset();

reset() deletes the cursor, outbox and application data together. This release replaces the sync migration history with a new baseline. Recreate existing browser databases before opening them with this version. Resetting discards queued local edits, so sync them before upgrading when possible.

Set syncOnReconnect: true to sync when the browser fires online or the page becomes visible. It defaults to false. Listeners attach on start() and detach on stop(). The online event also triggers sync while the page is hidden. Overlapping events share the active cycle. Outside a browser, this option has no effect.

The push and pull response shapes are exported as Zod schemas from @prisma-idb/sync-extension-idb/schemas: pushResultSchema and logWithRecordSchema.

On this page