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).
1. Enable a table
Section titled “1. Enable a table”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.
2. Use the SDK
Section titled “2. Use the SDK”pnpm add @potalab/base @potalab/base-syncimport { 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 | stoppedawait base.sync.resync() // drop the local copy and download againquery() supports an equality where (or a predicate), orderBy, ascending, limit and offset, and returns { data, error } like the rest of the SDK.
3. Storage and encryption
Section titled “3. Storage and encryption”| 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.
React Native
Section titled “React Native”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.
4. Offline writes
Section titled “4. Offline writes”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 noneawait 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 backbase.sync.status.pending // writes waiting to be sent- Every write is a mutation with a unique
mid(UUIDv7) and an HLCts, 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 inquery()/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
midwithduplicate. - Per mutation:
appliedstays visible until a pull delivers the row (aremoveof its tag, or an upsert whosectsstamps 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/supersededreplace the local row with the server’s (the columns that lost last-writer-wins disappear);rejected(includingmid_expired) removes the mutation, rolls the view back and callsonReject(later writes to a row whose insert was refused are dropped with reasondependency_rejected);retrykeeps it and resends with backoff (1 s doubling to 60 s). 429/503 honourRetry-After.clock_skewre-stamps the pending mutations to the server clock and resends them; amidwhose own time (it is a UUIDv7) is ahead of the server is replaced by a new one (the server never recorded it), soMutationResult.midcan differ from themidlater seen inonReject. - Entries older than 29 days are dropped (
onRejectreasonexpired), because the server forgetsmids 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.queryfilters in the driver (store.query, SQL on sqlite-wasm) when it has one, thewhereis plain equality and nothing is pending for the table.
Behaviour
Section titled “Behaviour”-
Changing the columns of a synced table is not detected. After an
ALTER TABLEthat adds, drops or retypes a column (or aGRANT/REVOKEon a column), runselect base.sync_bump_epoch();orPOST /v1/projects/{ref}/sync/resyncin 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
errorand the SDK retries afterRetry-After; no connection shows asofflineand the local data stays readable. -
removeevents 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.