Skip to main content
The Zero class is the primary client for Zero. It manages connections, queries, mutations, and real-time synchronization with your database.

Constructor

import { Zero } from '@rocicorp/zero';

const z = new Zero({
  userID: 'user-123',
  schema,
  auth: 'your-auth-token',
  cacheURL: 'https://myapp.zero.ms'
});
options
ZeroOptions
required
Configuration object for the Zero client

ZeroOptions

userID
string
required
A unique identifier for the user. Must be non-empty. Each userID gets its own client-side storage. This must match the sub claim of the auth token if auth is provided.
schema
Schema
required
The schema defining the tables and their relationships used in Zero.
cacheURL
string
URL to the zero-cache server. Can be:
  • A simple hostname: "https://myapp.zero.ms"
  • A prefix with a single path component: "https://myapp.zero.ms/zero"
auth
string | null | undefined
A token to identify and authenticate the user. Set to null or undefined if there is no logged in user.When auth changes while connected, Zero refreshes server-side auth context and re-transforms queries without reconnecting.When a 401 or 403 HTTP status code is received, Zero will transition to the needs-auth connection state.
storageKey
string
Distinguishes the storage used by this Zero instance from other instances with the same userID.
mutators
MutatorRegistry | CustomMutatorDefs
Custom mutator definitions. Client-side mutators must be idempotent as they can be rebased multiple times.Define mutators using defineMutator to create type-safe mutations:
mutators: {
  increment: defineMutator(({tx, args}) => 
    tx.mutate.counter.update({...})
  ),
  issues: {
    create: defineMutator(({tx, args}) => ...),
    close: defineMutator(({tx, args}) => ...)
  }
}
mutateURL
string
Custom URL for mutation requests sent to your API server.
mutateHeaders
Record<string, string>
Custom headers to include in mutation requests sent to your API server.
queryURL
string
Custom URL for query requests sent to your API server.
queryHeaders
Record<string, string>
Custom headers to include in query requests sent to your API server.
logLevel
'debug' | 'info' | 'warn' | 'error'
default:"error"
Determines the level of detail for logging. Messages are logged to the console.
kvStore
'mem' | 'idb' | StoreProvider
default:"idb"
Storage implementation to use on the client:
  • 'idb': IndexedDB storage (default) - persists data between sessions
  • 'mem': In-memory storage - data is not persisted
  • Custom function to create KV stores
hiddenTabDisconnectDelay
number
default:"300000"
Milliseconds to wait before disconnecting a Zero instance whose tab has become hidden. Default is 5 minutes.
disconnectTimeoutMs
number
default:"60000"
Milliseconds to wait before disconnecting when the connection has timed out. Default is 1 minute.
pingTimeoutMs
number
default:"5000"
Timeout in milliseconds for ping operations. Controls both idle time before sending a ping and wait time for pong response. Total time to detect a dead connection is 2 × pingTimeoutMs.
batchViewUpdates
(applyViewUpdates: () => void) => void
Integrates UI framework batching with Zero (e.g., React’s unstable_batchedUpdates or Solid’s batch). Implementations must call applyViewUpdates synchronously.
queryChangeThrottleMs
number
default:"10"
Milliseconds to wait before sending the next batch of query changes to the server.
slowMaterializeThreshold
number
default:"5000"
Milliseconds to wait for a materialization to complete before printing a warning to the console.
onUpdateNeeded
(reason: UpdateNeededReason) => void
Called when a client code update is needed. Default behavior is to reload the page. Provide your own function to prevent automatic reloading (e.g., display a toast notification).
onClientStateNotFound
() => void
Called when the client can no longer sync due to missing synchronization state. Default behavior is to reload the page.
context
Context
Context passed to queries when they are executed.

Properties

version
string
The version of the Zero client.
userID
string
The user ID for this Zero instance.
storageKey
string
The storage key for this Zero instance.
clientID
ClientID
The unique client ID for this instance of Zero.
server
string | null
The server URL that this Zero instance is configured with.
idbName
string
The name of the IndexedDB database in which the data of this instance is stored.
schemaVersion
string
The schema version of the data understood by this application.
schema
Schema
The schema passed into Zero when it was constructed.Can be paired with the inspector API to explore the client cache:
const inspector = __zero.inspector;
const client = inspector.client;
console.log('client map:', await client.map());

for (const tableName of Object.keys(__zero.schema.tables)) {
  console.table(await client.rows(tableName));
}
closed
boolean
Whether this Zero instance has been closed. Once closed, it no longer syncs and cannot be used for queries or mutations.
connection
Connection
The connection API for managing Zero’s connection lifecycle.
// Subscribe to connection state changes
z.connection.state.subscribe(state => {
  console.log('Connection state:', state.name);
});

// Manually resume connection from error state
await z.connection.connect();
mutate
ZeroMutate
Execute mutations. Call with registered custom mutators:
await z.mutate(
  mutators.myMutator({id: '1', title: 'First issue'}),
);
When schema.enableLegacyMutators is true, legacy conveniences are added:
  • Table-scoped CRUD helpers: z.mutate.issue.create / update / delete
  • Custom mutators exposed directly on z.mutate
await z.mutate.issue.create({id: '1', title: 'First issue'});
await z.mutate.myMutator({id: '1', title: 'Updated'});
mutateBatch
BatchMutator
deprecated
Batch multiple CRUD mutations together:
await z.mutateBatch(m => {
  await m.issue.create({id: '1', title: 'First issue'});
  await m.comment.create({id: '1', text: 'Comment', issueID: '1'});
});
All mutations in a batch are sent in a single transaction. If one fails, all are rolled back.Deprecated: Use z.mutate(mutationRequest) instead.
query
SchemaQuery
deprecated
Query builders for each table in the schema.Deprecated: Use createBuilder() to create query builders instead.
context
Context
The context passed to queries when they are executed.

Methods

run()

Executes a query once and returns the results.
// Wait for server sync
const users = await z.run(userQuery);

// Run with local data only
const cachedUsers = await z.run(userQuery, {type: 'unknown'});
query
Query | QueryRequest
required
The query to execute
runOptions
RunOptions
Options controlling query execution:
  • {type: 'complete'}: Wait for server sync (default)
  • {type: 'unknown'}: Run immediately with local data
returns
Promise<TReturn>
A promise resolving to the query results

materialize()

Creates a materialized view of a query that stays synchronized with the database.
// Create a standard view
const view = z.materialize(userQuery);
console.log(view.data); // Current query results
view.destroy(); // Clean up when done

// Create a custom view
const customView = z.materialize(userQuery, (query) => new MyCustomView(query));
query
Query | QueryRequest
required
The query to materialize
factory
ViewFactory
Optional factory function to create a custom view implementation
options
MaterializeOptions
Options controlling view behavior
returns
TypedView<TReturn> | T
A TypedView that stays synchronized with the data, or a custom view if factory is provided

preload()

Preloads data for a query into the cache without keeping it in memory.
const {complete, cleanup} = z.preload(userQuery);
await complete;
// Now the data is cached and can be used immediately
query
Query | QueryRequest
required
The query to preload
options
PreloadOptions
Options controlling preload behavior
returns
{complete: Promise<void>, cleanup: () => void}
An object with:
  • complete: Promise that resolves when data is loaded
  • cleanup: Function to cancel the preload

close()

Closes this Zero instance.
await z.close();
Once closed:
  • No longer syncs with the server
  • Cannot query or mutate data
  • Query views stop updating
returns
Promise<void>
A promise that resolves when the instance is closed

Build docs developers (and LLMs) love