Logo: Capacitor Offline First

Capacitor Offline First

Organisatioun
Cap-go
capacitor-offline-first

Guide to building offline-first Capacitor apps with data synchronization, caching strategies, and conflict resolution. Covers Fast SQL, service workers, and network detection. Use this skill when users need their app to work without internet.

Add to TypingMind

Iwwersiicht

EditeurCap-go
Repositorycapgo-skills
Skill-Nummcapacitor-offline-first
Stären
71
Forks
4
Matgeliwwert Dateien
1
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • 1 matgeliwwert Dateien

    Skripten, Virlagen a Referenzen, déi de Modell beim Schaffe liese kann. D'Dateie kënnen nëmme gelies ginn a ginn ni ausgeféiert.

  • Open Source

    Cap-go huet de Skill op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Capacitor Offline First an TypingMind, fir e mat all LLM ze benotzen, oder setzt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vu GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier, déi hei drënner steet, an a bestätegt d'Installatioun.
    https://github.com/Cap-go/capgo-skills/tree/main/plugins/capacitor-features/skills/capacitor-offline-first
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill derbäisetzen → Iwwer eng GitHub-URL. Pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an d'Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Cap-go/capgo-skills.git /tmp/capgo-skills
mkdir -p .claude/skills
cp -r /tmp/capgo-skills/plugins/capacitor-features/skills/capacitor-offline-first .claude/skills/capacitor-offline-first
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Capacitor Offline First an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Capacitor Offline First automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Capacitor Offline First net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Schlësselen.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

Offline-First Capacitor Apps

Build apps that work seamlessly with or without internet connectivity.

When to Use This Skill

  • User needs offline support
  • User asks about data sync
  • User wants caching
  • User needs local database
  • User has connectivity issues

Offline-First Architecture

┌─────────────────────────────────────────┐
│              UI Layer                    │
├─────────────────────────────────────────┤
│           Service Layer                  │
│  ┌─────────────┐  ┌─────────────────┐   │
│  │ Online Mode │  │ Offline Mode    │   │
│  └──────┬──────┘  └────────┬────────┘   │
├─────────┼──────────────────┼────────────┤
│         │    Sync Manager  │            │
│         └────────┬─────────┘            │
├──────────────────┼──────────────────────┤
│  ┌───────────────┴───────────────────┐  │
│  │         Local Database            │  │
│  │   (Fast SQL / IndexedDB)          │  │
│  └───────────────────────────────────┘  │
└─────────────────────────────────────────┘

Network Detection

Using Capacitor Network Plugin

bash
npm install @capacitor/network
npx cap sync
typescript
import { Network } from '@capacitor/network';

// Check current status
const status = await Network.getStatus();
console.log('Connected:', status.connected);
console.log('Connection type:', status.connectionType);

// Listen for changes
Network.addListener('networkStatusChange', (status) => {
  console.log('Network status changed:', status.connected);

  if (status.connected) {
    // Back online - sync data
    syncManager.syncPendingChanges();
  } else {
    // Offline - show indicator
    showOfflineIndicator();
  }
});

Network-Aware Service

typescript
import { Network } from '@capacitor/network';

class NetworkAwareService {
  private isOnline = true;

  constructor() {
    this.init();
  }

  private async init() {
    const status = await Network.getStatus();
    this.isOnline = status.connected;

    Network.addListener('networkStatusChange', (status) => {
      this.isOnline = status.connected;
    });
  }

  async fetch<T>(url: string, options?: RequestInit): Promise<T> {
    if (!this.isOnline) {
      // Return cached data
      return this.getCachedData(url);
    }

    try {
      const response = await fetch(url, options);
      const data = await response.json();

      // Cache the response
      await this.cacheData(url, data);

      return data;
    } catch (error) {
      // Network error - try cache
      return this.getCachedData(url);
    }
  }
}

Local Database with Fast SQL

Installation

bash
npm install @capgo/capacitor-fast-sql
npx cap sync

Before using Fast SQL in production, complete the required platform setup:

  • iOS: allow localhost networking for the plugin transport.
  • Android: add the localhost cleartext exception required by the plugin.
  • Web: install sql.js if the app needs the web fallback.

Use the dedicated sqlite-to-fast-sql skill when you need the full platform checklist.

Database Setup

typescript
import { KeyValueStore } from '@capgo/capacitor-fast-sql';

class Database {
  private store: Awaited<ReturnType<typeof KeyValueStore.open>> | null = null;

  async open() {
    if (this.store) return;
    this.store = await KeyValueStore.open({
      database: 'myapp',
      store: 'data',
      encrypted: false,
    });
  }

  async set(key: string, value: any) {
    await this.open();
    await this.store!.set(key, value);
  }

  async get<T>(key: string): Promise<T | null> {
    await this.open();
    return this.store!.get<T>(key);
  }

  async remove(key: string) {
    await this.open();
    await this.store!.remove(key);
  }

  async keys(): Promise<string[]> {
    await this.open();
    return this.store!.keys();
  }
}

Offline Data Repository

typescript
interface Entity {
  id: string;
  updatedAt: number;
  syncStatus: 'synced' | 'pending' | 'conflict';
}

class OfflineRepository<T extends Entity> {
  constructor(
    private db: Database,
    private collection: string
  ) {}

  getCollection(): string {
    return this.collection;
  }

  async getAll(): Promise<T[]> {
    const keys = await this.db.keys();
    const items: T[] = [];

    for (const key of keys) {
      if (key.startsWith(`${this.collection}:`)) {
        const item = await this.db.get<T>(key);
        if (item) items.push(item);
      }
    }

    return items;
  }

  async getById(id: string): Promise<T | null> {
    return this.db.get<T>(`${this.collection}:${id}`);
  }

  async save(item: T, options?: { markPending?: boolean }): Promise<void> {
    item.updatedAt = Date.now();
    if (options?.markPending ?? true) {
      item.syncStatus = 'pending';
    }
    await this.db.set(`${this.collection}:${item.id}`, item);
  }

  async delete(id: string): Promise<void> {
    // Soft delete - mark for sync
    const item = await this.getById(id);
    if (item) {
      item.syncStatus = 'pending';
      (item as any).deleted = true;
      await this.db.set(`${this.collection}:${id}`, item);
    }
  }

  async getPending(): Promise<T[]> {
    const all = await this.getAll();
    return all.filter((item) => item.syncStatus === 'pending');
  }

  async markSynced(id: string): Promise<void> {
    const item = await this.getById(id);
    if (item) {
      item.syncStatus = 'synced';
      await this.db.set(`${this.collection}:${id}`, item);
    }
  }
}

Sync Manager

typescript
import { Network } from '@capacitor/network';

class SyncManager {
  private isSyncing = false;
  private syncQueue: Array<() => Promise<void>> = [];

  constructor(private repositories: OfflineRepository<any>[]) {
    this.setupNetworkListener();
  }

  private setupNetworkListener() {
    Network.addListener('networkStatusChange', async (status) => {
      if (status.connected) {
        await this.syncAll();
      }
    });
  }

  async syncAll() {
    if (this.isSyncing) return;
    this.isSyncing = true;

    try {
      for (const repo of this.repositories) {
        await this.syncRepository(repo);
      }
    } finally {
      this.isSyncing = false;
    }
  }

  private async syncRepository(repo: OfflineRepository<any>) {
    const pending = await repo.getPending();

    for (const item of pending) {
      try {
        if ((item as any).deleted) {
          await this.deleteRemote(item);
        } else {
          await this.syncToRemote(item);
        }
        await repo.markSynced(item.id);
      } catch (error) {
        console.error('Sync failed for item:', item.id, error);
        // Keep as pending for retry
      }
    }

    // Pull remote changes
    await this.pullRemoteChanges(repo);
  }

  private async syncToRemote(item: any) {
    await fetch(`/api/${item.collection}/${item.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(item),
    });
  }

  private async deleteRemote(item: any) {
    await fetch(`/api/${item.collection}/${item.id}`, {
      method: 'DELETE',
    });
  }

  private async pullRemoteChanges(repo: OfflineRepository<any>) {
    const lastSync = await this.getLastSyncTime(repo);
    const collection = repo.getCollection();
    const response = await fetch(
      `/api/${collection}?since=${lastSync}`
    );
    const remoteItems = await response.json();

    for (const remoteItem of remoteItems) {
      const localItem = await repo.getById(remoteItem.id);

      if (!localItem) {
        // New item from server
        await repo.save({ ...remoteItem, syncStatus: 'synced' }, { markPending: false });
      } else if (localItem.syncStatus === 'synced') {
        // No local changes - update from server
        await repo.save({ ...remoteItem, syncStatus: 'synced' }, { markPending: false });
      } else {
        // Conflict - local has pending changes
        await this.resolveConflict(localItem, remoteItem, repo);
      }
    }

    await this.setLastSyncTime(repo, Date.now());
  }

  private async resolveConflict(
    local: any,
    remote: any,
    repo: OfflineRepository<any>
  ) {
    // Last-write-wins strategy
    if (local.updatedAt > remote.updatedAt) {
      // Keep local, re-sync to server
      local.syncStatus = 'pending';
      await repo.save(local);
    } else {
      // Server wins
      await repo.save({ ...remote, syncStatus: 'synced' }, { markPending: false });
    }
  }
}

Service Worker Caching

Register Service Worker

typescript
// src/main.ts
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js');
}

Service Worker with Workbox

typescript
// public/sw.js
import { precacheAndRoute } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate, CacheFirst, NetworkFirst } from 'workbox-strategies';

// Precache static assets
precacheAndRoute(self.__WB_MANIFEST);

// Cache API responses
registerRoute(
  ({ url }) => url.pathname.startsWith('/api/'),
  new NetworkFirst({
    cacheName: 'api-cache',
    networkTimeoutSeconds: 5,
  })
);

// Cache images
registerRoute(
  ({ request }) => request.destination === 'image',
  new CacheFirst({
    cacheName: 'image-cache',
    plugins: [
      {
        expiration: {
          maxEntries: 100,
          maxAgeSeconds: 7 * 24 * 60 * 60, // 1 week
        },
      },
    ],
  })
);

// Cache fonts
registerRoute(
  ({ request }) => request.destination === 'font',
  new CacheFirst({
    cacheName: 'font-cache',
  })
);

Optimistic UI Updates

typescript
class TodoService {
  constructor(
    private repo: OfflineRepository<Todo>,
    private syncManager: SyncManager
  ) {}

  async addTodo(text: string): Promise<Todo> {
    const todo: Todo = {
      id: crypto.randomUUID(),
      text,
      completed: false,
      updatedAt: Date.now(),
      syncStatus: 'pending',
    };

    // Save locally immediately
    await this.repo.save(todo);

    // Trigger sync in background
    this.syncManager.syncAll().catch(console.error);

    return todo;
  }

  async toggleComplete(id: string): Promise<Todo> {
    const todo = await this.repo.getById(id);
    if (!todo) throw new Error('Todo not found');

    todo.completed = !todo.completed;
    await this.repo.save(todo);

    this.syncManager.syncAll().catch(console.error);

    return todo;
  }
}

Queue Failed Requests

typescript
class RequestQueue {
  private queue: QueuedRequest[] = [];

  constructor(private storage: Database) {
    this.loadQueue();
  }

  private async loadQueue() {
    this.queue = await this.storage.get<QueuedRequest[]>('requestQueue') || [];
  }

  private async saveQueue() {
    await this.storage.set('requestQueue', this.queue);
  }

  async enqueue(request: QueuedRequest) {
    this.queue.push(request);
    await this.saveQueue();
  }

  async processQueue() {
    const status = await Network.getStatus();
    if (!status.connected) return;

    while (this.queue.length > 0) {
      const request = this.queue[0];

      try {
        await fetch(request.url, {
          method: request.method,
          headers: request.headers,
          body: request.body,
        });

        this.queue.shift();
        await this.saveQueue();
      } catch (error) {
        // Stop processing on failure
        break;
      }
    }
  }
}

Best Practices

1. Show Sync Status

tsx
function SyncIndicator() {
  const { isOnline, pendingChanges, isSyncing } = useSyncStatus();

  if (!isOnline) {
    return <Badge color="warning">Offline</Badge>;
  }

  if (isSyncing) {
    return <Badge color="info">Syncing...</Badge>;
  }

  if (pendingChanges > 0) {
    return <Badge color="warning">{pendingChanges} pending</Badge>;
  }

  return <Badge color="success">Synced</Badge>;
}

2. Handle Conflicts Gracefully

typescript
async function handleConflict(local: Todo, remote: Todo): Promise<Todo> {
  // Option 1: Last write wins
  return local.updatedAt > remote.updatedAt ? local : remote;

  // Option 2: Merge changes
  return {
    ...remote,
    ...local,
    updatedAt: Math.max(local.updatedAt, remote.updatedAt),
  };

  // Option 3: Ask user
  const choice = await showConflictDialog(local, remote);
  return choice === 'local' ? local : remote;
}

3. Validate Before Sync

typescript
function validateTodo(todo: Todo): boolean {
  if (!todo.id || !todo.text) return false;
  if (todo.text.length > 500) return false;
  return true;
}

async function syncTodo(todo: Todo) {
  if (!validateTodo(todo)) {
    throw new Error('Invalid todo');
  }
  // Proceed with sync
}

Resources

Matgeliwwert Dateien

De Modell liest dës Dateie bei Bedarf, wärend de Skill gelueden ass. Si ginn als liesbar Dateie bereetgestallt a ginn ni ausgeféiert.

Heefeg gestallte Froen

Wat mécht de KI-Skill Capacitor Offline First?

Guide to building offline-first Capacitor apps with data synchronization, caching strategies, and conflict resolution. Covers Fast SQL, service workers, and network detection. Use this skill when users need their app to work without internet.

Firwat Capacitor Offline First op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Capacitor Offline First besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt, amplaz en Abonnement pro Benotzerplaz ze bezuelen. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Capacitor Offline First an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/Cap-go/capgo-skills/tree/main/plugins/capacitor-features/skills/capacitor-offline-first an. TypingMind liest d'Datei SKILL.md, bëndelt déi zougehéiereg Dateien an installéiert dat Ganzt als Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Capacitor Offline First benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Capacitor Offline First benotzen?

Esou vill wéi Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Capacitor Offline First domat benotzen – zum Beispill mat GPT, Claude, Gemini, Grok, DeepSeek, Mistral oder Llama – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Capacitor Offline First gratis?

Cap-go huet de Skill op GitHub publizéiert. Kuckt am Repository no de Lizenzbedéngungen. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbare Pak vun Instruktiounen, deen engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt e maache soll a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a kee Lafzäitëmfeld a funktionéiere mat all Modell.

Alleguer weisen

Elo Ären eegene KI-Aarbechtsberäich ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇