Skip to main content

Working with Storage Solutions

1. Using Ionic Storage

Ionic Storage is a simple key-value storage system for Ionic apps, built on top of localStorage, IndexedDB, or SQLite depending on the platform and configuration.

Property Description Default
driverOrder Array of drivers to use in order of preference. Options: 'indexeddb', 'sqlite', 'localstorage'. ['indexeddb', 'sqlite', 'localstorage']
name Name of the database (used for SQLite and IndexedDB). 'ionic-storage'
version Version of the database (used for IndexedDB). 1.0
size Size of the database (used for SQLite). 1

Example: Initializing Ionic Storage

import { defineCustomElements } from '@ionic/core/loader';
import { IonicStorageModule } from '@ionic/storage-angular';

// Define custom elements for Ionic Core
defineCustomElements();

// Configure storage in app.module.ts or app.component.ts
IonicStorageModule.forRoot({
  driverOrder: ['sqlite', 'indexeddb', 'localstorage'],
  name: 'my-app-db',
  version: 1.0,
  size: 1
})

Example: Storing and Retrieving Data

import { Storage } from '@ionic/storage-angular';

constructor(private storage: Storage) {
  this.storage.create();
}

async setData() {
  await this.storage.set('user', { name: 'John Doe', email: 'john@example.com' });
}

async getData() {
  const user = await this.storage.get('user');
  console.log(user); // { name: 'John Doe', email: 'john@example.com' }
}
Note: Ionic Storage is asynchronous and requires await when using methods like set(), get(), and remove().
Warning: On web platforms, localStorage is used by default. It has a storage limit of around 5MB and is synchronous, which can cause performance issues in large applications.

2. Setting Storage Values

Method Description Parameters Notes
setItem(key, value) Sets a key-value pair in storage key: string, value: string Stores data as string; use JSON.stringify for objects
setObject(key, value) Stores an object in storage key: string, value: object Automatically serializes object to JSON

Example: Setting a simple value

import { Storage } from '@ionic/storage-angular';

constructor(private storage: Storage) {
  this.storage.create();
}

async setValue() {
  await this.storage.set('username', 'john_doe');
}

Example: Setting an object value

import { Storage } from '@ionic/storage-angular';

constructor(private storage: Storage) {
  this.storage.create();
}

async setObjectValue() {
  const user = { name: 'John', age: 30 };
  await this.storage.setObject('user', user);
}

3. Getting Storage Values

Method Description Return Type Notes
storage.get(key) Retrieves the value associated with the given key from storage Promise<string | null> Resolves with the stored value or null if not found
storage.keys() Retrieves all keys currently stored Promise<string[]> Useful for iterating over all stored items
storage.length() Gets the number of items in storage Promise<number> Can be used to check storage size

Example: Retrieving a Stored Value

import { Plugins } from '@capacitor/core';

const { Storage } = Plugins;

async function getValue() {
  const value = await Storage.get({ key: 'userToken' });
  console.log('Retrieved value:', value);
}

getValue();

Example: Getting All Keys

import { Plugins } from '@capacitor/core';

const { Storage } = Plugins;

async function getAllKeys() {
  const keys = await Storage.keys();
  console.log('All stored keys:', keys);
}

getAllKeys();
Note: The Storage plugin uses an asynchronous API. Always await the result when retrieving values.

4. Removing Storage Items

Method Description Notes
remove(key) Removes the item with the specified key from storage Async operation, returns Promise
clear() Removes all items from storage Async operation, returns Promise

Example: Removing a Storage Item

import { Storage } from &#x27;@ionic/storage-angular&#x27;;

async function removeItem() {
  await Storage.remove(&#x27;userPreferences&#x27;);
  console.log(&#x27;User preferences removed&#x27;);
}

Example: Clearing All Storage

import { Storage } from &#x27;@ionic/storage-angular&#x27;;

async function clearStorage() {
  await Storage.clear();
  console.log(&#x27;All storage cleared&#x27;);
}
Note: The remove and clear methods are asynchronous and must be awaited to ensure proper execution.

5. Clearing Storage

Method Description Notes
clear() Removes all stored data from the storage system Useful for resetting app state or cleaning up old data

Example: Clearing All Storage

import { Storage } from &#x27;@ionic/storage-angular&#x27;;

async function clearAllStorage() {
  await storage.clear();
  console.log(&#x27;All storage cleared&#x27;);
}
Note: The clear() method removes all data from the storage system, including any keys or values stored by the app. Use with caution in production environments.

6. Iterating Storage Keys

Method Description Notes
keys() Returns an array of all keys in the storage Async method, requires await

Example: Iterating Storage Keys

import { Storage } from &#x27;@ionic/storage-angular&#x27;;

async function iterateKeys() {
  const keys = await storage.keys();
  console.log(&#x27;Storage keys:&#x27;, keys);
  keys.forEach(key => {
    console.log(&#x27;Key:&#x27;, key);
  });
}
Note: The keys() method returns all keys in the storage, which can be useful for debugging or managing storage content.

7. Configuring Storage Drivers

Driver Description Usage Notes
SQLite Local database for mobile apps import { SQLiteConnection } from '@ionic/storage' Best for offline-first apps
IndexedDB Browser-based NoSQL storage import { IndexDB } from '@ionic/storage' Works in web browsers
LocalStorage Simple key-value storage in browser import { LocalStorage } from '@ionic/storage' Small data only, no types
SecureStorage Encrypted storage for sensitive data import { SecureStorage } from '@ionic/storage' Android/iOS only

Example: Setting up SQLite Driver

import { Storage } from '@ionic/storage';
import { SQLiteConnection } from '@ionic/storage';

const storage = new Storage({
  name: 'mydb',
  driverOrder: [SQLiteConnection]
});

await storage.create();
Note: Ensure the appropriate Cordova/ Capacitor plugins are installed for native drivers.

8. Using SQLite Driver

Property Description Default Notes
driver Driver to use for database operations 'sqlite' Must be set to 'sqlite' for SQLite support
database Name of the database file 'app.db' File path relative to app root
version Database version for migration support 1 Used for schema migrations
location Storage location for the database 'default' Options: 'default', 'bundled'

Example: Initializing SQLite Driver

import { SQLiteDB } from '@ionic/storage';

const db = new SQLiteDB({
  driver: 'sqlite',
  database: 'myapp.db',
  version: 2,
  location: 'default'
});

await db.open();

Example: Creating a Table

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

Example: Inserting Data

const result = await db.execute(
  'INSERT INTO users (name, email) VALUES (?, ?)',
  ['John Doe', 'john@example.com']
);

console.log('Inserted row ID:', result.lastId);

Example: Querying Data

const users = await db.execute('SELECT * FROM users WHERE email = ?', ['john@example.com']);
console.log(users);
Note: The SQLite driver in Ionic is built on top of sql.js, which runs entirely in the browser using WebAssembly. This means all database operations are synchronous and must be handled carefully to avoid blocking the UI.

9. Implementing Secure Storage

Method Description Notes
secureStorage.set(key, value) Sets a key-value pair in secure storage Stores data encrypted on device
secureStorage.get(key) Retrieves a value by key from secure storage Returns the stored value or null if not found
secureStorage.remove(key) Removes a key-value pair from secure storage Deletes the entry associated with the key
secureStorage.keys() Retrieves all keys stored in secure storage Useful for iterating over stored items

Example: Storing and Retrieving Data

import { SecureStorage } from '@ionic-native/secure-storage';

const secureStorage = new SecureStorage();

secureStorage.set('userToken', 'abc123xyz').then(() => {
  console.log('Token stored');
});

secureStorage.get('userToken').then((value) => {
  console.log('Retrieved token:', value);
});
Note: Secure storage is platform-specific and uses native encryption on iOS and Android.
Warning: Do not store sensitive data in regular local storage as it's not encrypted.

10. Managing Storage Quota

Storage Type Quota Limit Notes
Local Storage 5MB Default limit per origin in most browsers
IndexedDB 50MB Higher limit, can be increased by user permission
SQLite Unlimited Depends on device storage and OS limits
File System API Unlimited Requires explicit user permission and browser support

Example: Check Storage Usage

import { Plugins } from '@ionic/core';

const { Storage } = Plugins;

async function checkStorageUsage() {
  const storageInfo = await Storage.get({ key: 'storage_info' });
  console.log('Storage Info:', storageInfo);
}

checkStorageUsage();
Note: Quota limits can vary between browsers and platforms. Always implement fallbacks or user prompts for storage management.

Was this article helpful?