Local-First Client
Learn how to set up the local-first browser client, from bundler config to local storage and sync.The local-first client keeps a replica of the data each user can read in the browser. Queries answer from it instantly, writes show up before they sync, and the app keeps working offline. It loads as its own chunk on top of the thin client.
When to pick it
Jazz has two browser clients. Both use the same schema, queries, permissions and Db API, so you
can start thin and upgrade to local-first
later without changing app code.
| Thin Client | Local-First Client | |
|---|---|---|
| Bundle | about 160 KB gzipped | adds the Wasm engine (about 3.1 MB gzipped), loaded as its own chunk |
| Queries run | on your backend, under the user's policies | in the browser, against a local replica |
| Writes show up | after one round trip | instantly, then sync |
| Offline | no | yes, reads and writes |
| Local storage | none | IndexedDB, per account |
| Wasm and workers | none | a Wasm engine in a shared worker |
| Setup | nothing beyond JazzProvider | a client loader and a few bundler lines |
Both need React 19 or later for the React bindings (jazz-tools declares react >=19, so npm
refuses to install it next to React 18).
Pick the thin client by default. Pick local-first when users need instant UI on every change, work offline, or keep large working sets that should not round-trip on every read.
Connect
Pass a loader for the local-first client. The app starts thin, then upgrades in the background after the first load:
App.tsximport { JazzProvider } from "jazz-tools/react";function Root() {return (<JazzProviderconfig={{ serverUrl: "/jazz", client: () => import("jazz-tools/local-first") }}signedOut={<SignIn />}><App /></JazzProvider>);}
app.tsexport async function createDeviceAccountSession() {return createJazzClient({serverUrl: "/jazz",// Start as a device account: a guest, with no sign-in.initial: "device",// Local data, so the guest works offline from its first visit.client: () => import("jazz-tools/local-first"),});}
The background upgrade to the local-first client keeps the same Db: its live queries, listeners and writes carry on. db.isLocalFirst() tells whether it has happened yet, the session snapshot's localFirst field says the same and changes when the upgrade happens (to show "offline support ready", or notice the app is still thin), and await db.upgradeToLocalFirst(loader) waits for it. If the app took the Db offline with disconnect(), it stays offline. In the browser, a local-first Db is offline for every tab of the app, so at the upgrade that also takes the app's other local-first tabs offline. Signing in, signing out and switching accounts do give the session a new Db. The old one then ends its live queries with a DbReplacedError (from "jazz-tools") and throws it on writes. Follow the session to pick up the new one, and read session.db again for each write (it throws while no one is signed in):
app.ts/*** Run `attach` on the session's current Db, and again each time the session* replaces it: when the user signs in, signs out or switches accounts. (The* upgrade to the local-first client keeps the same Db.)*/export function followDb(session: JazzSession<JazzClient>,attach: (db: Db) => () => void,): () => void {let current: Db | undefined;let detach: (() => void) | undefined;const follow = () => {const next = session.getSnapshot().client?.db;if (next === current) return;detach?.();detach = undefined;current = next;if (next) detach = attach(next);};const stop = session.subscribe(follow);follow();return () => {stop();detach?.();};}
const stop = followDb(session, (db) => db.subscribe(app.todos, renderTodos));session.db.insert(app.todos, { title: "Buy milk", done: false });
The framework providers do this for you.
Once an account has used the local-first client in a browser, Jazz opens it with that client on future visits, so it works offline. If the switch to local-first fails, Jazz keeps using the thin client and logs a warning; that tab tries again on its next reload. Loading the page itself offline is up to your app: cache the app shell, including Jazz's Wasm and worker files, with a service worker of your own.
To open the local-first client straight away for every account, first visit included, pass
localFirst: "now" next to client (the default is "background": start thin, upgrade after the
first load). Use it when the app must work offline from the first render, or when it uses
db.transaction, which only the local-first client has. Otherwise keep the default, which renders
sooner. With "now", a loader that fails makes the session fail (status: "error") instead of
running thin, and "now" without client is refused.
The import() stays in your code, so the Wasm engine (about 3.1 MB gzipped, 8.7 MB uncompressed)
downloads only when the client upgrades. After the first render, local storage keeps filling for a
few seconds. Writes made on the thin client before the upgrade are kept offline only when a query
the client subscribes to covers them. The local-first chunk and Wasm load lazily, so when you deploy
a new build, keep the previous builds' hashed assets available for a while: tabs still open on the
old build fetch them when they upgrade. To
upgrade only on demand, call useDb().upgradeToLocalFirst(() => import("jazz-tools/local-first"))
instead; see Upgrading to local-first.
Sign-in
Both clients sign in the same way: they ask your main backend at /jazz who is signed in, with
your app's own session cookie, and your backend's authenticate decides who that user is. The
client asks on start, when the page regains focus and when another tab signs in or out. After your
own sign-in or sign-out, call refresh() on the session (from useJazzSession() in React, Vue and
Solid, getJazzSession() in Svelte) so the change shows at once. To let people in before they sign
up, start them as guests on a device account (initial: "device"),
a local-first friendly account whose key stays on the device. The browser never holds a Jazz key or token. See How Auth Works.
Reads and writes
Both clients return the same Db: queries, subscribe, insert, update,
upsert, delete, transactions and the framework hooks work unchanged.
- Thin client. A write shows after one round trip to your backend.
wait({ tier })resolves once the server has committed the write, whichever tier you pass: that already meets every tier. - Local-first client. A write shows instantly in every local query, then syncs.
wait({ tier })takes a durability tier (localorglobal) to wait for the point you need.
Both take the same call, for example await db.insert(app.todos, todo).wait({ tier: "global" }),
so code that waits works on either client.
Options
Both clients take these options, in createJazzClient(config) or <JazzProvider config={…}>:
| Option | Default | What it does |
|---|---|---|
serverUrl | /jazz | Where your main backend mounts Jazz. Set it only if you mount it somewhere else |
initial | "signed-out" | "device" starts visitors as guests on a device account |
linkDeviceAccountOnSignUp | true | Link the device account to a user who signs up; turn off on shared devices |
clearOnSignOut | false | Wipe the account's local data on sign-out, for shared devices |
createJazzClient needs a config ({} for the defaults) and refuses an option it doesn't take, naming
the ones it does, rather than ignoring it.
Both clients also set window.__jazz, the page's sync status and storage controls for tests and
agents (window.__jazz.status(), waitForSync(), clearStorage()). The name is Jazz's: if your
app or another library already set window.__jazz, Jazz leaves it alone, warns once on the
console and goes without the handle. Rename your own global to get the handle back.
The local-first client also takes:
| Option | Default | What it does |
|---|---|---|
driver | { type: "persistent" } | Where the replica lives: IndexedDB, or { type: "memory" } for nothing on disk |
localFirst | "background" | "now" opens local-first from the first render instead of upgrading after it |
dbName | derived from your endpoint | Logical base name of the local database; Jazz keeps one per endpoint and account |
runtimeSources | found automatically | Where to load the Wasm and worker from; see Wasm and workers |
logLevel | "warn" | Wasm log level, for debugging |
Local storage
By default the replica lives in IndexedDB, kept apart per endpoint and account (jazz-idb, plus one
database per account named with its URL-encoded account id), so two users on the same browser never
share data. driver: { type: "memory" } keeps it in memory only, and it is
gone when the tab closes. await db.deleteClientStorage() clears the current one; see
Resetting browser storage.
An app upgraded from alpha.59 that had guests on device accounts passes its old app ID as scope
(createJazzClient({ scope: "<your alpha.59 app ID>" })), so those guests keep their accounts. New
apps leave it out. See Upgrading from alpha.59.
What stays on the device:
- Signing out closes the account's client but keeps its local data, synced rows included, for that
user's next sign-in, and the remembered user (account, identity and claims, never a credential)
stays in
localStorage. On shared devices, passclearOnSignOut: true; see the shared device checklist. It wipes the account's data, but the empty per-account database and the list of account ids on this device remain. - Your schema, including tables a user can't read, ships in the app bundle. Permissions decide which rows a user can read, not which tables they can see exist.
Eviction
{ type: "persistent" } writes to IndexedDB. By default browsers treat this as best-effort storage — under disk pressure, or after long inactivity, the browser can clear it without warning. For a local-first app that means a returning user can find their identity (the device account key) and any data owned only by that user wiped.
The trade-offs are:
- Best-effort (default). No prompt, no friction. Acceptable when the server holds a copy of every row the user cares about, or when the app gracefully reseeds from sync. Anything that exists only on this device is at risk.
- Persistent. Storage is only cleared by an explicit user action (clearing site data, uninstalling). Required for true offline-first apps and for any data that doesn't round-trip through a server. Browsers gate this behind
navigator.storage.persist(), which may show a prompt or grant silently based on engagement heuristics.
To request persistent storage, call it once after the user has signed in or interacted enough that a prompt makes sense:
if (navigator.storage?.persist) {const granted = await navigator.storage.persist();if (!granted) {// Fall back: rely on sync, warn the user, or retry later.}}
Check navigator.storage.persisted() on subsequent loads to see whether the grant is still in effect. Pair this with the backup and restore flow so the device account key can be recovered if storage is ever cleared.
Offline and guests
Reads and writes keep working offline and sync when the connection returns. A signed-out visitor
can also start as a guest on a device account
(initial: "device"): an account whose key is created on the device, which works offline and keeps
its data when the visitor signs up later.
Wasm and workers
Bundler config
There is no Jazz plugin to add for Vite or Next.js. In development, run your app as usual: createJazz in your
main backend is the dev server, and it publishes your schema, permissions
and migrations every time it starts.
The local-first client loads Jazz's Wasm in the browser, and your backend loads Jazz's native module
(jazz-napi) on the server. If your bundler touches either, tell it to leave them alone:
vite.config.tsimport { defineConfig } from "vite";export default defineConfig({// plugins: your framework's plugin (React, Vue, Svelte, Solid, SvelteKit) ...// Load the Wasm as a real module instead of pre-bundling it.optimizeDeps: { exclude: ["jazz-wasm"] },});
jazz-wasm is the only package to exclude. Vite still pre-bundles jazz-tools under vite dev,
and Jazz then has the dev server load its worker from the jazz-tools package. Before alpha.62,
Vite 6 and 7 also needed jazz-tools excluded; keeping that exclude does no harm.
It needs Vite 6 or later: Vite 5 answers the local-first chunk with a 500, "Vite is unable to
parse the worker options as the value is not static". This is the same for React, Vue, Svelte,
Solid and SvelteKit. With pnpm, also add jazz-wasm as a
direct dependency of your app so its strict layout resolves it.
SvelteKit also needs ssr: { external: ["jazz-napi"] } in the same config, because its server
runs Jazz too: without it, vite build bundles Jazz's native module and fails with "Cannot find
module './index.cjs'".
next.config.tsimport type { NextConfig } from "next";const nextConfig: NextConfig = {// Your backend loads Jazz's native module; Next must not bundle it.serverExternalPackages: ["jazz-napi"],};export default nextConfig;
metro.config.jsconst { getDefaultConfig } = require("expo/metro-config");const { withJazz } = require("jazz-tools/expo/metro");// Metro doesn't find Jazz's Wasm and worker on its own.module.exports = withJazz(getDefaultConfig(__dirname));
This is for the web target of an Expo app. After adding it, start Metro with
npx expo start --clear. Don't set runtimeSources.brokerWorkerUrl there:
the worker is the chunk Metro builds.
The thin client has no Wasm, so it needs no Vite line or
Metro config. A
Next.js app that imports jazz-tools/backend still needs serverExternalPackages.
Wasm loading
Use runtimeSources when Jazz can't automatically find its internal assets. This usually only happens with non-standard bundler configurations.
| Field | Use it when |
|---|---|
runtimeSources.baseUrl | Jazz runtime assets are served from a shared base path like /assets/jazz/ |
runtimeSources.wasmUrl | The Wasm file has an explicit public URL |
runtimeSources.brokerWorkerUrl | The browser broker worker has an explicit public URL |
runtimeSources.wasmVersion | An immutable deployed build version for configured browser asset URLs |
runtimeSources.wasmSource | Your runtime gives you Wasm bytes directly |
runtimeSources.wasmModule | Your runtime gives you a precompiled WebAssembly.Module |
Jazz resolves these in this order:
runtimeSources.wasmModuleruntimeSources.wasmSourceruntimeSources.wasmUrl/runtimeSources.brokerWorkerUrlruntimeSources.baseUrl- built-in zero-config fallback
Use baseUrl when both assets live together under one public directory. Use explicit wasmUrl /
brokerWorkerUrl when your app serves them from different places.
For browser URL overrides, also set wasmVersion to an immutable value that changes whenever
either the Wasm or broker-worker build changes (for example, your deployment's asset manifest
version). Jazz adds that value to the asset URLs you configure and to the SharedWorker's name, so
a rolling deployment cannot reuse a long-lived SharedWorker with bytes fetched from an older build
at the same URL. Without a bundler, also set brokerWorkerUrl or baseUrl, so the worker script URL
is versioned too. Your asset host must serve these URLs with query strings intact.
Worker failures
If the browser worker stops responding, Jazz reports an error. An operation that was in progress may
still have completed, so check its result before retrying it. Jazz never clears local storage on
its own; if the worker stays stuck, await db.deleteClientStorage() recovers it (see
Resetting browser storage).