# Offline-first apps
Source: https://sovaria.in/docs/offline-first

Keep reading, querying, listening and writing documents with no connection; everything syncs in order when it comes back.

Turn on offline mode once and documents keep working without a network: reads and queries answer from a local cache, live listeners keep firing, and writes are applied locally at once and queued. When the connection returns, the queue is sent in the original order. It works in browsers, React Native and Node.

Browser:
```js
import { createClient, indexedDbStorage } from '@sovaria/sdk'

const sov = createClient('https://<ref>.sovarias.in', '<anon key>')
const offline = sov.enableOffline({
  storage: indexedDbStorage(),                                 // survives reloads
  onSyncError: (error, writes) => console.warn('refused by the server', error, writes),
})

await sov.collection('todos').add({ title: 'works on a plane', done: false })   // instant, even offline
const stop = await sov.collection('todos').where('done', '==', false).onSnapshot((snap) => {
  render(snap.docs.map((d) => ({ ...d.data, saving: d.hasPendingWrites })))
})
await offline.pendingWrites()   // what still has to reach the server
```

React Native:
```js
import AsyncStorage from '@react-native-async-storage/async-storage'
import { createClient, keyValueStorage } from '@sovaria/sdk'

const sov = createClient(projectUrl, anonKey)
sov.enableOffline({ storage: keyValueStorage(AsyncStorage) })
```

Firestore API:
```js
import { initializeFirestore, persistentLocalCache } from '@sovaria/sdk/firestore'

const db = initializeFirestore(sov, { localCache: persistentLocalCache() })
// snap.metadata.fromCache / snap.metadata.hasPendingWrites work as in Firebase
```

## How it behaves

|  | Online | Offline |
|---|---|---|
| Read a document | From the server; the cache is refreshed | From the cache (`fromCache`); a document never read before fails with `NETWORK_ERROR` |
| Query and count | From the server; results are cached | Run on the cached documents of the collection with the same operators, ordering, cursors and limits |
| Live listeners | Pushed changes | Keep firing from the cache, including your own offline writes (`hasPendingWrites`); a listener started offline answers from the cache |
| Writes and batches | Committed at once | Applied to the cache at once (field transforms too: `increment`, `arrayUnion`, `serverTimestamp`…) and queued |
| Transactions | Run on the server | Fail with `NETWORK_ERROR`: their reads must be current, as in Firebase |

- When the connection is back (the browser's `online` event, the next successful request, or every 30 seconds) the queue is sent one commit at a time, oldest first, so the server sees the writes in the order you made them.
- A queued write the server refuses — a collection rule, a row policy, a version precondition — is dropped, reported to `onSyncError`, and the cache is put back to the server's version of those documents. When the refusal only says the outcome of an earlier try is unknown (`409 IDEMPOTENCY_OUTCOME_UNKNOWN`, after a server error), `onSyncError` gets that first server error.
- A write the platform was too busy to take (a `503` refused before any work) is queued like an offline one; a rate limit (`429`), a server error or a refusal is returned to you.
- Every write keeps one `Idempotency-Key` from its first try through every replay, so a replay whose answer was lost is not applied twice — while the server still remembers the key, which is an hour. A write that stays queued longer than that (the device offline all afternoon) is sent as new: if its first try may have reached the server, check before relying on it.
- Access rules still apply: nothing in the queue skips them, and the cache only holds documents this user was allowed to read.
- Call `offline.clear()` when a user signs out, so the next user of the device doesn't see their cache or queue.
- The cache holds at most `maxCached` documents (default 5,000; the least recently cached go first, never one with a queued write) and the queue at most `maxQueued` writes (default 1,000). A write past that fails at once with `OFFLINE_QUEUE_FULL` until the queue drains: `sov.enableOffline({ storage, maxCached: 20000, maxQueued: 5000 })`.
- Query results are saved to the cache in the background in one batch, so an offline-enabled query answers as fast as a plain one.

## Where the cache lives

| Storage | Use it for |
|---|---|
| `indexedDbStorage()` | Browsers: survives reloads and restarts. |
| `keyValueStorage(AsyncStorage)` | React Native, or any store with getItem / setItem / removeItem / getAllKeys. |
| `memoryStorage()` | The default: tests, servers, or a cache that ends with the page. |
