Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท State and Storage

Storage, Preferences and SQLite

Choose the right storage for an Ionic app: Capacitor Preferences for small settings, SQLite for structured data, Filesystem for files and secure storage for secrets.

Where should a mobile app keep its data? The browser offers localStorage and IndexedDB, and Capacitor adds native options. The wrong choice can silently lose user data, because mobile operating systems may clear web storage when space is low. This lesson compares the options, shows the real APIs and gives you stand-ins to practice the patterns: key-value storage with JSON, and structured storage with migrations.

The options

Storage Good for Notes
localStorage / IndexedDB web builds, caches may be evicted by the OS on a phone
Capacitor Preferences small settings, flags, tokens (not secrets) native key-value store, async, strings only
SQLite (@capacitor-community/sqlite) lists, relations, search, large data real database, survives restarts and web view clearing
Filesystem photos, documents, exports see Camera and Filesystem
Secure storage plugins passwords, refresh tokens Keychain on iOS, Keystore on Android

A good rule: settings go to Preferences, anything you would call "records" goes to SQLite, big binary data goes to files, and secrets go to secure storage, never to Preferences.

Preferences

Terminal
npm install @capacitor/preferences
npx cap sync
TypeScript
import { Preferences } from '@capacitor/preferences';

await Preferences.set({ key: 'theme', value: 'dark' });
const { value } = await Preferences.get({ key: 'theme' });   // 'dark' or null
await Preferences.remove({ key: 'theme' });
const { keys } = await Preferences.keys();
await Preferences.clear();

Values are strings. Objects must be serialized, and reads can return null for a missing key. Because everything is asynchronous, a first render happens before the value arrives; show defaults and update, or load settings before showing the page (for instance in an app initializer).

A small typed wrapper avoids repeating JSON code:

TypeScript
export async function load<T>(key: string, fallback: T): Promise<T> {
  const { value } = await Preferences.get({ key });
  if (value === null) return fallback;
  try { return JSON.parse(value) as T; } catch { return fallback; }
}
export const save = (key: string, data: unknown) =>
  Preferences.set({ key, value: JSON.stringify(data) });
JS A typed Preferences wrapper

Press Run (or Ctrl + Enter) to see the console output here.

No output.

SQLite

For lists with filtering, sorting and relations, use a database. The community plugin provides SQLite on Android and iOS (and an IndexedDB-backed version on the web through jeep-sqlite). Real code, read-only:

TypeScript
import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';

const sqlite = new SQLiteConnection(CapacitorSQLite);
const db = await sqlite.createConnection('app', false, 'no-encryption', 1, false);
await db.open();

await db.execute(`
  CREATE TABLE IF NOT EXISTS notes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    body TEXT NOT NULL DEFAULT '',
    updated_at INTEGER NOT NULL
  );
`);

await db.run('INSERT INTO notes (title, updated_at) VALUES (?, ?)', ['Pack tent', Date.now()]);
const result = await db.query('SELECT * FROM notes WHERE title LIKE ? ORDER BY updated_at DESC', ['%tent%']);
console.log(result.values);

Always pass values as parameters (?), never by gluing strings together, to avoid SQL injection and quoting bugs. For SQL itself, our SQL tutorial teaches the language in a runnable environment.

Migrations

Apps live for years and users update at different times, so the schema must change safely. Keep a version number and an ordered list of migrations. At startup, run those newer than the stored version.

JS A migration runner

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Never edit a migration that has shipped. Users who already ran it will not run it again, so your change would reach only new installs. Add a new migration instead.

Secrets and backups

Refresh tokens and passwords belong in the platform keychain (iOS Keychain, Android Keystore) through a secure storage plugin. Preferences is plain text on the device. Also remember that Android and iCloud backups may copy app data, so exclude sensitive files if needed.

flowchart TD
  A["What are you storing?"] --> B{"Secret?"}
  B -->|"Yes"| C["Secure storage"]
  B -->|"No"| D{"Records, search, relations?"}
  D -->|"Yes"| E["SQLite"]
  D -->|"No"| F{"Binary or large?"}
  F -->|"Yes"| G["Filesystem"]
  F -->|"No"| H["Preferences"]

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should important data not live only in localStorage on a phone?

    Web view storage can be cleared by the system, while Preferences and SQLite are native.
  2. 2. What type of value does Preferences.set accept?

    Serialize objects with JSON.stringify and parse them when reading.
  3. 3. A migration already shipped but has a mistake. What do you do?

    Existing installs will not rerun the old migration, so fixes must be new steps.
  4. 4. Where should a refresh token be stored?

    Secrets need hardware-backed or OS-protected storage.

Summary

  • Preferences is for small string settings; wrap it with JSON helpers and defaults.
  • SQLite is for records and queries; use parameters and migrations.
  • Files go to the Filesystem; secrets go to secure storage.
  • Web view storage can be cleared by the OS.
  • Never edit shipped migrations.

Next: Offline First and Sync