or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-ionic--storage

A simple key-value storage utility for Ionic apps with automatic storage engine selection and cross-platform support

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@ionic/storage@4.0.x

To install, run

npx @tessl/cli install tessl/npm-ionic--storage@4.0.0

index.mddocs/

Ionic Storage

Ionic 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.

Package Information

  • Package Name: @ionic/storage
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @ionic/storage

For Angular applications, use the separate @ionic/storage-angular package instead:

npm install @ionic/storage-angular

Core Imports

import { Storage, Drivers, StorageConfig } from "@ionic/storage";

For CommonJS:

const { Storage, Drivers } = require("@ionic/storage");

Basic Usage

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}`);
});

Architecture

Ionic Storage is built around several key components:

  • Storage Class: Main interface providing all key-value operations with Promise-based API
  • Driver System: Pluggable storage backends with automatic selection and fallback support
  • Configuration System: Flexible configuration for database names, driver priorities, and LocalForage options
  • Cross-Platform Support: Seamless operation across web (IndexedDB/localStorage) and native platforms (SQLite)
  • Enterprise Features: Optional encryption support through Ionic Secure Storage for security-sensitive applications

Capabilities

Storage Instance Creation

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;
}

Database Initialization

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();

Driver Management

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();

Key-Value Operations

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();

Storage Information

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)}`);
});

Encryption Support

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' });

Driver Constants

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'
};

Types

/**
 * Database instance type (LocalForage compatible)
 */
type Database = any;

/**
 * Driver type for storage engines
 */
type Driver = any;

Error Handling

The Storage class throws specific errors for common failure scenarios:

  • Database not initialized: Thrown when calling methods before create()
  • Secure storage not available: Thrown when calling setEncryptionKey() without the enterprise driver
try {
  await storage.get('key');
} catch (error) {
  if (error.message.includes('Database not created')) {
    console.error('Storage not initialized. Call create() first.');
  }
}

Platform Support

  • Web: IndexedDB (preferred), LocalStorage (fallback)
  • Capacitor/Cordova: SQLite (with additional driver), IndexedDB, LocalStorage
  • Enterprise: Ionic Secure Storage with 256-bit AES encryption

Configuration Examples

Basic Configuration

const storage = new Storage({
  name: 'myApp',
  storeName: 'keyvaluepairs'
});

Custom Driver Order

const storage = new Storage({
  name: 'myApp',
  driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage]
});

SQLite Support (Cordova/Capacitor)

import CordovaSQLiteDriver from 'localforage-cordovasqlitedriver';

const storage = new Storage({
  driverOrder: [CordovaSQLiteDriver._driver, Drivers.IndexedDB, Drivers.LocalStorage]
});

await storage.defineDriver(CordovaSQLiteDriver);

Secure Storage (Enterprise)

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');