Guide to building offline-first Capacitor apps with data synchronization, caching strategies, and conflict resolution. Covers SQLite, service workers, and network detection. Use this skill when users need their app to work without internet.
npx playbooks add skill cap-go/capacitor-skills --skill capacitor-offline-first
TRIGGER when:
Plugin not implemented)Do not use:
@capacitor-community/sqlite / Ionic secure storage: sqlite-to-fast-sqlcapgo-live-updatescapacitor-securitycapacitor-performance| Question | Default answer |
|----------|----------------|
| Where does UI read from? | Local DB only. Network writes into the DB; UI observes the DB. |
| Storage for records | SQLite via @capgo/capacitor-fast-sql |
| Storage for small settings / tokens | @capacitor/preferences (not for secrets; see capacitor-security) |
| localStorage / IndexedDB | Transient only: iOS can evict WebView storage under pressure |
| App shell offline | Already offline: Capacitor bundles web assets in the binary (or Capgo live-update bundle). No service worker needed. |
| Service worker in native builds | Avoid. Android SW blocks Capacitor plugin injection; iOS SW needs WKAppBoundDomains, which also blocks injection unless ios.limitsNavigationsToAppBoundDomains is set. Keep SW for the PWA build only. |
| IDs | Client-generated UUIDs (crypto.randomUUID()), so offline creates need no server round trip |
| Conflict policy | Ask the user/product owner: last-write-wins per record, per-field merge, or server-authoritative with user review |
| Deletes | Soft delete (tombstone) until the server acknowledges |
localStorage, @capacitor/preferences, other SQLite plugins), API shape (does it support updated_since / version fields / idempotency keys?), auth refresh flow, existing service worker registration.npm install @capgo/capacitor-fast-sql @capacitor/network && npx cap sync, then the platform setup in [references/fast-sql-setup.md](references/fast-sql-setup.md) (required: iOS ATS local networking, Android localhost cleartext).networkStatusChange -> connected, App resume, after each local write (debounced), optional background task.Only load a reference when its topic is in play.
import { FastSQL } from '@capgo/capacitor-fast-sql';
import { Network } from '@capacitor/network';
import { App } from '@capacitor/app';
const db = await FastSQL.connect({ database: 'app' });
await db.execute(`CREATE TABLE IF NOT EXISTS outbox (
id TEXT PRIMARY KEY, entity TEXT NOT NULL, op TEXT NOT NULL,
payload TEXT NOT NULL, created_at INTEGER NOT NULL, attempts INTEGER NOT NULL DEFAULT 0
)`);
export async function saveTodo(todo: Todo) {
await db.transaction(async (tx) => {
await tx.run('INSERT OR REPLACE INTO todos (id, text, done, updated_at, dirty) VALUES (?, ?, ?, ?, 1)',
[todo.id, todo.text, todo.done ? 1 : 0, Date.now()]);
await tx.run('INSERT INTO outbox (id, entity, op, payload, created_at) VALUES (?, ?, ?, ?, ?)',
[crypto.randomUUID(), 'todo', 'upsert', JSON.stringify(todo), Date.now()]);
});
void sync(); // fire and forget; sync() is single-flight
}
Network.addListener('networkStatusChange', (s) => { if (s.connected) void sync(); });
App.addListener('resume', () => void sync());
The data row and its outbox entry are written in one transaction so a crash cannot leave one without the other.
Network.getStatus().connected === true does not mean the API is reachable (captive portals, VPN, server down). Treat fetch failures as offline; use connected only as a hint to retry.networkStatusChange can fire several times in a row; make sync() single-flight.@capacitor/filesystem and keep the path in the DB.resume is the reliable path.grep -rn "serviceWorker.register" src/ | grep -v "isNativePlatform" # should be empty or web-guarded
/usr/libexec/PlistBuddy -c "Print :NSAppTransportSecurity:NSAllowsLocalNetworking" ios/App/App/Info.plist
grep -n "networkSecurityConfig\|usesCleartextTraffic" android/app/src/main/AndroidManifest.xml
SELECT COUNT(*) FROM outbox exposed in a debug screen, or pull the file (adb exec-out run-as com.example.app ls databases/).| Error / symptom | Cause | Fix |
|-----------------|-------|-----|
| "CapgoCapacitorFastSql" plugin is not implemented on android / Plugin not implemented | Service worker or WKAppBoundDomains blocking injection, or missing npx cap sync | Remove SW from native build / set ios.limitsNavigationsToAppBoundDomains; run npx cap sync |
| iOS: The resource could not be loaded because the App Transport Security policy requires the use of a secure connection | Fast SQL localhost transport blocked by ATS | Add NSAllowsLocalNetworking |
| Android: CLEARTEXT communication to localhost not permitted by network security policy | Cleartext to localhost blocked | Add network_security_config.xml localhost exception |
| SQLITE_CONSTRAINT: UNIQUE constraint failed during pull | Server row id already exists locally | Use INSERT ... ON CONFLICT(id) DO UPDATE |
| database is locked | Parallel writers / long transaction | Serialize writes; keep transactions short; single-flight sync |
| Data gone after iOS storage pressure | Stored in localStorage / IndexedDB | Move to SQLite |
| Duplicate server records after reconnect | Retried POST without idempotency key | Send outbox id as Idempotency-Key; server dedupes |
Weekly roundup of top Claude Code skills, MCP servers, and AI coding tips.