A simple key-value storage utility for Ionic apps with automatic storage engine selection and cross-platform support
npx @tessl/cli install tessl/npm-ionic--storage@4.0.0Ionic Storage is a simple key-value storage utility for Ionic apps that provides a unified interface for data persistence across different platforms and storage engines. It automatically selects the best available storage engine on each platform (IndexedDB, localStorage, SQLite for native apps) without requiring direct interaction with the underlying storage mechanisms.
npm install @ionic/storageFor Angular applications, use the separate @ionic/storage-angular package instead:
npm install @ionic/storage-angularimport { Storage, Drivers, StorageConfig } from "@ionic/storage";For CommonJS:
const { Storage, Drivers } = require("@ionic/storage");import { Storage } from "@ionic/storage";
// Create and initialize storage
const storage = new Storage();
await storage.create();
// Basic operations
await storage.set('name', 'Mr. Ionitron');
const name = await storage.get('name');
await storage.remove('name');
await storage.clear();
// Information about stored data
const keys = await storage.keys();
const count = await storage.length();
// Iterate through all data
await storage.forEach((value, key, iterationNumber) => {
console.log(`${key}: ${value}`);
});Ionic Storage is built around several key components:
Create and configure a Storage instance with optional configuration.
/**
* Create a new Storage instance using the order of drivers and any additional config
* options to pass to LocalForage.
*/
class Storage {
constructor(config?: StorageConfig);
}
interface StorageConfig {
/** Database name (default: '_ionicstorage') */
name?: string;
/** Database version */
version?: number;
/** Database size limit */
size?: number;
/** Store name within database (default: '_ionickv') */
storeName?: string;
/** Database description */
description?: string;
/** Array specifying driver priority order */
driverOrder?: Driver[];
/** Database key (default: '_ionickey') */
dbKey?: string;
}Initialize the storage instance and set up drivers. Must be called before any data operations.
/**
* Initialize the storage instance and set up drivers
* @returns Promise resolving to the Storage instance
*/
create(): Promise<Storage>;Usage Example:
const storage = new Storage({
name: 'myApp',
driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage]
});
await storage.create();Define custom storage drivers before initialization.
/**
* Define a new Driver. Must be called before initializing the database.
* @param driver - Driver implementation to register
* @returns Promise from LocalForage.defineDriver
*/
defineDriver(driver: any): Promise<any>;
/**
* Get the name of the driver being used
* @returns Name of the current driver or null if not initialized
*/
get driver(): string | null;Usage Example:
import CordovaSQLiteDriver from 'localforage-cordovasqlitedriver';
const storage = new Storage({
driverOrder: [CordovaSQLiteDriver._driver, Drivers.IndexedDB]
});
await storage.defineDriver(CordovaSQLiteDriver);
await storage.create();Core storage operations for setting, getting, and removing data.
/**
* Get the value associated with the given key
* @param key - The key to identify this value
* @returns Promise with the value of the given key
*/
get(key: string): Promise<any>;
/**
* Set the value for the given key
* @param key - The key to identify this value
* @param value - The value for this key
* @returns Promise that resolves when the key and value are set
*/
set(key: string, value: any): Promise<any>;
/**
* Remove any value associated with this key
* @param key - The key to identify this value
* @returns Promise that resolves when the value is removed
*/
remove(key: string): Promise<any>;
/**
* Clear the entire key value store. WARNING: HOT!
* @returns Promise that resolves when the store is cleared
*/
clear(): Promise<void>;Usage Examples:
// Store different data types
await storage.set('user', { name: 'John', id: 123 });
await storage.set('settings', { theme: 'dark', notifications: true });
await storage.set('lastLogin', new Date().toISOString());
// Retrieve data
const user = await storage.get('user');
const theme = await storage.get('settings');
const lastLogin = await storage.get('lastLogin');
// Remove specific items
await storage.remove('user');
// Clear all data
await storage.clear();Methods to inspect and enumerate stored data.
/**
* Get the number of keys stored
* @returns Promise that resolves with the number of keys stored
*/
length(): Promise<number>;
/**
* Get all stored keys
* @returns Promise that resolves with the keys in the store
*/
keys(): Promise<string[]>;
/**
* Iterate through each key,value pair
* @param iteratorCallback - Callback function called for each item
* @returns Promise that resolves when the iteration has finished
*/
forEach(
iteratorCallback: (value: any, key: string, iterationNumber: number) => any
): Promise<void>;Usage Examples:
// Check storage size
const count = await storage.length();
console.log(`Storage contains ${count} items`);
// List all keys
const allKeys = await storage.keys();
console.log('Stored keys:', allKeys);
// Process all stored data
await storage.forEach((value, key, iterationNumber) => {
console.log(`Item ${iterationNumber}: ${key} = ${JSON.stringify(value)}`);
});Enable encryption when using Ionic Secure Storage driver (enterprise feature).
/**
* Set encryption key for secure storage
* @param key - Encryption key string
* @throws Error if @ionic-enterprise/secure-storage not installed
*/
setEncryptionKey(key: string): void;Usage Example:
import IonicSecureStorageDriver from '@ionic-enterprise/secure-storage/driver';
const storage = new Storage({
driverOrder: [Drivers.SecureStorage, Drivers.IndexedDB, Drivers.LocalStorage]
});
await storage.defineDriver(IonicSecureStorageDriver);
await storage.create();
// Enable encryption
storage.setEncryptionKey('mySecretKey');
// All subsequent operations will be encrypted
await storage.set('sensitiveData', { token: 'abc123' });Pre-defined driver identifiers for configuration.
const Drivers = {
/** Ionic Secure Storage driver identifier (enterprise) */
SecureStorage: 'ionicSecureStorage',
/** IndexedDB driver identifier */
IndexedDB: 'asyncStorage',
/** LocalStorage driver identifier */
LocalStorage: 'localStorageWrapper'
};/**
* Database instance type (LocalForage compatible)
*/
type Database = any;
/**
* Driver type for storage engines
*/
type Driver = any;The Storage class throws specific errors for common failure scenarios:
create()setEncryptionKey() without the enterprise drivertry {
await storage.get('key');
} catch (error) {
if (error.message.includes('Database not created')) {
console.error('Storage not initialized. Call create() first.');
}
}const storage = new Storage({
name: 'myApp',
storeName: 'keyvaluepairs'
});const storage = new Storage({
name: 'myApp',
driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage]
});import CordovaSQLiteDriver from 'localforage-cordovasqlitedriver';
const storage = new Storage({
driverOrder: [CordovaSQLiteDriver._driver, Drivers.IndexedDB, Drivers.LocalStorage]
});
await storage.defineDriver(CordovaSQLiteDriver);import IonicSecureStorageDriver from '@ionic-enterprise/secure-storage/driver';
const storage = new Storage({
driverOrder: [Drivers.SecureStorage, Drivers.IndexedDB, Drivers.LocalStorage]
});
await storage.defineDriver(IonicSecureStorageDriver);
await storage.create();
storage.setEncryptionKey('your-encryption-key');