Skip to content

Local-first (offline reads and writes)

Phase 1 of local-first sync is read-only offline: the SDK downloads the rows a user can read (your RLS policy decides) into a local database, keeps it up to date, and lets the app query it with no network. Writes work offline too: they are saved in a local outbox, shown at once, and sent when the connection is back (section 4).

In the dashboard, open Database > Offline sync. Type the table (public.todos), press Check policy to see the advisor findings, then Enable sync. The page lists every synced table with its primary key, soft-delete setting and current advisor warnings, and Disable turns a table off again. Enabling and disabling need the project admin role; developers can read the list and run the check.

Or do the same in SQL as the project owner (role admin):

SELECT * FROM base.sync_policy_check('public.todos');
SELECT base.enable_sync('public.todos');

The same is available in the Management API (/v1/projects/{ref}/sync/*). The policy must be a pure function of the data (no now(), no volatile functions), the table needs a single-column primary key and RLS on. A user can sync at most 50 000 visible rows per table.

Terminal window
pnpm add @potalab/base @potalab/base-sync
import { createClient } from '@potalab/base'
import { withSync, indexedDbStoreFactory } from '@potalab/base-sync'
const base = withSync(createClient({ url, key }), { store: indexedDbStoreFactory() })
await base.auth.signInWithPassword({ email, password })
await base.sync.start() // bootstrap, then pull every 30 s and when the browser goes online
const { data } = await base.sync.table('todos').query({ where: { done: false }, orderBy: 'created_at', limit: 20 })
const stop = base.sync.table('todos').subscribe(({ data }) => render(data))
base.sync.onStatusChange((s) => console.log(s.state)) // idle | syncing | offline | error | stopped
await base.sync.resync() // drop the local copy and download again

query() supports an equality where (or a predicate), orderBy, ascending, limit and offset, and returns { data, error } like the rest of the SDK.

Driver Use
memoryStoreFactory() (default) Node, tests, SSR; lost on reload
indexedDbStoreFactory() browsers, persistent
expoSqliteStoreFactory / opSqliteStoreFactory from @potalab/base-sync/react-native React Native and Expo, SQLite, persistent
your own StoreFactory e.g. sqlite-wasm on OPFS (not bundled because of its size)
withSync(base, { store: indexedDbStoreFactory(), encryptionKey: async (userId) => myAesGcmKey(userId) })

The app supplies a WebCrypto AES-GCM key; row values are stored encrypted. Table names, row tags and the sync cursor are not.

import * as SQLite from 'expo-sqlite'
import { expoSqliteStoreFactory, cipherStoreFactory } from '@potalab/base-sync/react-native'
const store = cipherStoreFactory(expoSqliteStoreFactory(SQLite), (name) => ({
encrypt: (plain) => myNativeEncrypt(plain, key), // your own crypto: React Native has no crypto.subtle by default
decrypt: (data) => myNativeDecrypt(data, key),
}))
withSync(base, { store })

opSqliteStoreFactory({ open: (name) => open({ name }), remove: (name) => deleteDb(name) }) does the same for @op-engineering/op-sqlite, and rnSqliteStoreFactory({ open, remove }) accepts any library through the small SqlExecutor interface (run, all, transaction, close). expo-sqlite (SDK 51+, openDatabaseAsync) and op-sqlite are optional peer dependencies: install the one you use. The schema is the sqlite-wasm one (rows, meta), list(prefix) works through a small registry database, so user-switch purging and destroy behave as on the web. Pass encryptedStoreFactory(store, getKey, subtle) instead when your runtime has WebCrypto. SQL filtering (store.query) is available on unwrapped stores only.

const todos = base.sync.table('todos')
const { data, error } = await todos.insert({ title: 'buy milk' }) // { mid, pk }; the primary key is a UUIDv7 when you give none
await todos.update(pk, { done: true })
await todos.delete(pk) // soft delete
base.sync.onReject((m) => toast(`could not save ${m.op} on ${m.table}: ${m.reason}`)) // server refused; the local change is already rolled back
base.sync.status.pending // writes waiting to be sent
  • Every write is a mutation with a unique mid (UUIDv7) and an HLC ts, saved in the local database (outbox, same driver as the rows, so it is encrypted with the same key and survives a reload). It shows in query() / subscribe() at once: the query result is the server rows with the pending mutations applied on top, so a pull never overwrites a change that is not confirmed yet.
  • When online, the cycle is: check tables, bootstrap if needed, push (batches of at most 200 mutations / about 0.9 MB, in order), then pull. Resending is safe: the server answers a repeated mid with duplicate.
  • Per mutation: applied stays visible until a pull delivers the row (a remove of its tag, or an upsert whose cts stamps are at least the stamp the server gave the write; a pull that merely “caught up” is not enough because a long-running transaction can hold the change back), or for at most 2 minutes; merged / superseded replace the local row with the server’s (the columns that lost last-writer-wins disappear); rejected (including mid_expired) removes the mutation, rolls the view back and calls onReject (later writes to a row whose insert was refused are dropped with reason dependency_rejected); retry keeps it and resends with backoff (1 s doubling to 60 s). 429/503 honour Retry-After. clock_skew re-stamps the pending mutations to the server clock and resends them; a mid whose own time (it is a UUIDv7) is ahead of the server is replaced by a new one (the server never recorded it), so MutationResult.mid can differ from the mid later seen in onReject.
  • Entries older than 29 days are dropped (onReject reason expired), because the server forgets mids after 30 days. Sign-out, a different user, and a 401/403 delete the local database and therefore the outbox: unsent writes are lost on purpose.
  • SyncTable.query filters in the driver (store.query, SQL on sqlite-wasm) when it has one, the where is plain equality and nothing is pending for the table.
  • Changing the columns of a synced table is not detected. After an ALTER TABLE that adds, drops or retypes a column (or a GRANT/REVOKE on a column), run select base.sync_bump_epoch(); or POST /v1/projects/{ref}/sync/resync in the same migration so every client downloads again.

  • Several browser tabs can share one local database: with a single-connection driver (OPFS) wrap it in sharedStoreFactory(...), which elects one tab with Web Locks.

  • After an epoch change or when the server’s change log no longer covers your cursor (410), local rows are dropped and downloaded again.

  • Rate limits (429) and busy servers (503) show as error and the SDK retries after Retry-After; no connection shows as offline and the local data stays readable.

  • remove events carry only an opaque per-user tag, and each pull sends a Bloom filter of the tags you hold, so a client learns nothing about rows it never held.