Chapter 6 of 12 ~14 min read

Storage & Preferences

Side-by-side Cordova vs Capacitor — practical migration with working code.


Key-Value Storage

Cordova Storage / LocalStorage
// Ionic Storage 3 with Cordova
import { Storage } from '@ionic/storage-angular';

// Set
await this.storage.set('token', 'abc123');

// Get
const token = await this.storage.get('token');

// Remove
await this.storage.remove('token');

// Clear all
await this.storage.clear();
Capacitor Preferences
// npm install @capacitor/preferences
import { Preferences } from '@capacitor/preferences';

// Set — always stores as string
await Preferences.set({
  key: 'token',
  value: 'abc123'
});

// Get
const { value } = await Preferences.get({
  key: 'token'
});
console.log(value); // 'abc123' | null

// Remove
await Preferences.remove({ key: 'token' });

// Clear all
await Preferences.clear();
Preferences stores strings only

Always JSON.stringify() objects and JSON.parse() when reading. For large datasets, use SQLite.

// Storing objects
await Preferences.set({
  key: 'user',
  value: JSON.stringify({ name: 'Alice', age: 30 })
});
const { value } = await Preferences.get({ key: 'user' });
const user = value ? JSON.parse(value) : null;

SQLite (Community Plugin)

Capacitor SQLite
// npm install @capacitor-community/sqlite
import { CapacitorSQLite, SQLiteConnection }
  from '@capacitor-community/sqlite';

const sqlite = new SQLiteConnection(CapacitorSQLite);

async function openDB() {
  const db = await sqlite.createConnection(
    'mydb', false, 'no-encryption', 1, false
  );
  await db.open();

  await db.execute(`
    CREATE TABLE IF NOT EXISTS users (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      email TEXT
    )
  `);

  await db.run('INSERT INTO users (name) VALUES (?)', ['Alice']);
  const res = await db.query('SELECT * FROM users');
  console.log(res.values);

  await sqlite.closeConnection('mydb', false);
}