### Basic IonicStorageModule Setup Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/ionic-storage-module.md Example of basic setup for IonicStorageModule in an Angular app.module.ts file. ```typescript import { NgModule } from '@angular/core'; import { IonicStorageModule } from '@ionic/storage-angular'; @NgModule({ imports: [ IonicStorageModule.forRoot() ] }) export class AppModule { } ``` -------------------------------- ### IonicStorageModule Setup with Custom Configuration Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/ionic-storage-module.md Example of setting up IonicStorageModule with custom configuration options, including name, version, storeName, and driverOrder. ```typescript import { NgModule } from '@angular/core'; import { Drivers } from '@ionic/storage'; import { IonicStorageModule } from '@ionic/storage-angular'; @NgModule({ imports: [ IonicStorageModule.forRoot({ name: '__mydb', version: 1.0, storeName: '_ionickv', driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage] }) ] }) ``` -------------------------------- ### Storage Constructor Configuration Example Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/types.md Demonstrates how to instantiate the Storage class with custom configuration options. This example sets a specific database name, version, store name, description, driver order, and size. ```typescript import { Storage, Drivers } from '@ionic/storage'; const storage = new Storage({ name: 'my_app_database', version: 1.0, storeName: 'app_data', description: 'Main application data store', driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage], size: 1024 * 1024 * 5 // 5MB }); ``` -------------------------------- ### Install Ionic Secure Storage Driver Source: https://github.com/ionic-team/ionic-storage/blob/main/README.md Follow the official installation guide to set up and install the @ionic-enterprise/secure-storage package. ```bash Follow the [official installation guide](https://ionic.io/docs/secure-storage) to set up and install `@ionic-enterprise/secure-storage`. ``` -------------------------------- ### Install localForage-CordovaSQLiteDriver Source: https://github.com/ionic-team/ionic-storage/blob/main/README.md Install the npm library for the localForage-CordovaSQLiteDriver. ```bash npm install localforage-cordovasqlitedriver ``` -------------------------------- ### Angular Module Configuration Example Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/types.md Shows how to configure Ionic Storage within an Angular module using IonicStorageModule.forRoot. This example specifies the database name and driver order for the application-wide storage instance. ```typescript import { NgModule } from '@angular/core'; import { Drivers } from '@ionic/storage'; import { IonicStorageModule } from '@ionic/storage-angular'; @NgModule({ imports: [ IonicStorageModule.forRoot({ name: 'my_app_database', driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage] }) ] }) export class AppModule { } ``` -------------------------------- ### Install Ionic Storage Source: https://github.com/ionic-team/ionic-storage/blob/main/README.md Install the core Ionic Storage library using npm. This is for general JavaScript projects. ```shell npm install @ionic/storage ``` -------------------------------- ### Complete Workflow for Secure Storage Setup Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/errors.md Illustrates the full process of defining, creating, and safely using setEncryptionKey() with the secure storage driver. ```typescript import { Drivers } from '@ionic/storage'; import IonicSecureStorageDriver from '@ionic-enterprise/secure-storage/driver'; const storage = new Storage({ driverOrder: [Drivers.SecureStorage, Drivers.IndexedDB, Drivers.LocalStorage] }); // Step 1: Define the driver await storage.defineDriver(IonicSecureStorageDriver); // Step 2: Create the storage instance await storage.create(); // Step 3: Now setEncryptionKey() is safe to call try { storage.setEncryptionKey('encryption-key-from-vault'); console.log('Encryption enabled'); } catch (error) { console.error('Encryption not available:', error.message); // App can continue with unencrypted storage } ``` -------------------------------- ### Usage Pattern Example Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/README.md Demonstrates a typical usage pattern for initializing and creating storage. This code can be copied and used directly in applications. ```typescript // ✓ Usage pattern (can be copied) const storage = new Storage(); await storage.create(); ``` -------------------------------- ### Install Capacitor SQLite Plugin Source: https://github.com/ionic-team/ionic-storage/blob/main/README.md Install the cordova-sqlite-storage plugin for Capacitor projects. ```bash npm install cordova-sqlite-storage ``` -------------------------------- ### Initialize Storage in React, Vue, or Vanilla JS Source: https://github.com/ionic-team/ionic-storage/blob/main/README.md Initialize the Storage instance and create the storage connection. This is the basic setup for non-Angular projects. ```typescript import { Storage } from '@ionic/storage'; const store = new Storage(); await store.create(); ``` -------------------------------- ### Handle SecureStorage Installation or Driver Order Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/migration-guide.md Resolve 'SecureStorage not installed' errors by either installing the `@ionic-enterprise/secure-storage` package or by adjusting the `driverOrder` to exclude SecureStorage. ```typescript // Option 1: Install Secure Storage npm install @ionic-enterprise/secure-storage // Option 2: Change driver order const storage = new Storage({ driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage] }); ``` -------------------------------- ### Install CordovaSQLiteDriver Packages Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/configuration.md Install the necessary packages for using the CordovaSQLiteDriver with Capacitor or Cordova. ```bash # Capacitor npm install cordova-sqlite-storage npm install localforage-cordovasqlitedriver # Cordova ionic cordova plugin add cordova-sqlite-storage npm install localforage-cordovasqlitedriver ``` -------------------------------- ### Install Cordova SQLite Plugin Source: https://github.com/ionic-team/ionic-storage/blob/main/README.md Install the cordova-sqlite-storage plugin for Cordova projects. ```bash ionic cordova plugin add cordova-sqlite-storage ``` -------------------------------- ### Install @ionic-enterprise/secure-storage Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/errors.md Shows the npm command to install the secure storage package. ```bash # First install the enterprise package npm install @ionic-enterprise/secure-storage # Then register it before using setEncryptionKey() ``` -------------------------------- ### Initialize Storage in Vanilla JS/React/Vue Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/module-overview.md Basic setup for using Ionic Storage in non-Angular applications. Ensure the storage is created before use. ```typescript import { Storage, Drivers } from '@ionic/storage'; const storage = new Storage(); await storage.create(); await storage.set('key', 'value'); ``` -------------------------------- ### Initialize Storage in React/Vue Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/README.md Basic setup for initializing Ionic Storage in React or Vue applications. Ensure `create()` is called before use. ```typescript import { Storage } from '@ionic/storage'; const storage = new Storage(); await storage.create(); ``` -------------------------------- ### Install SQLite Drivers Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/migration-guide.md Install the necessary npm packages for Cordova SQLite storage and the LocalForage Cordova SQLite driver. ```bash npm install cordova-sqlite-storage npm install localforage-cordovasqlitedriver ``` -------------------------------- ### Avoid Secure Storage Error: Install and Register Driver Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/errors.md Demonstrates the incorrect way to call setEncryptionKey() without the secure storage driver and the correct way after installing and registering it. ```typescript // ❌ Error: setEncryptionKey() without installing SecureStorage const storage = new Storage(); storage.setEncryptionKey('my-key'); // Throws error // ✓ Correct: Install and register the driver first import IonicSecureStorageDriver from '@ionic-enterprise/secure-storage/driver'; const storage = new Storage({ driverOrder: [Drivers.SecureStorage, Drivers.IndexedDB] }); await storage.defineDriver(IonicSecureStorageDriver); await storage.create(); storage.setEncryptionKey('my-key'); // Now safe ``` -------------------------------- ### Install Ionic Storage for Angular Source: https://github.com/ionic-team/ionic-storage/blob/main/README.md Install the Angular-specific Ionic Storage library using npm. Use this if you are building an Angular application. ```shell npm install @ionic-storage-angular ``` -------------------------------- ### Install Cordova SQLite Plugin and LocalForage Adapter Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/drivers.md Install the necessary npm packages for using the Cordova SQLite driver with Ionic Storage. ```bash # Install the plugin npm install cordova-sqlite-storage # Install the LocalForage adapter npm install localforage-cordovasqlitedriver ``` -------------------------------- ### Initialize Storage in Angular Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/README.md Angular-specific setup using `IonicStorageModule`. Storage is typically injected and `create()` is called during component initialization. ```typescript import { IonicStorageModule } from '@ionic/storage-angular'; @NgModule({ imports: [IonicStorageModule.forRoot()] }) export class AppModule { } // In component/service, inject Storage and call create() constructor(private storage: Storage) {} async ngOnInit() { await this.storage.create(); } ``` -------------------------------- ### Storage Initialization Pattern Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/README.md Ensures Storage is ready for operations by calling `create()` before any other methods like `set()` or `get()`. ```typescript const storage = new Storage(); await storage.create(); // Required await storage.set('key', 'value'); // Safe after create() ``` -------------------------------- ### NoopStorage Example Usage Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/helpers.md Demonstrates how to use NoopStorage in a server context and contrasts it with the standard Storage usage in a browser context. This highlights how NoopStorage provides a safe fallback for storage operations during SSR. ```typescript // In server context (Node.js) const storage = new NoopStorage(); await storage.create(); const user = await storage.get('user'); // Returns null, no error // In browser context const storage = new Storage(); await storage.create(); const user = await storage.get('user'); // Returns actual stored value ``` -------------------------------- ### Main Methods Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/README.md Provides an overview of the primary methods available for interacting with Ionic Storage, such as creating, getting, setting, removing, and clearing data. ```APIDOC ## API Reference Summary ### Main Methods | Method | Purpose | Returns | |--------|---------|---------| | `create()` | Initialize storage | `Promise` | | `get(key)` | Retrieve value by key | `Promise` | | `set(key, value)` | Store value by key | `Promise` | | `remove(key)` | Delete value by key | `Promise` | | `clear()` | Delete all values | `Promise` | | `keys()` | Get all keys | `Promise` | | `length()` | Get number of items | `Promise` | | `forEach(callback)` | Iterate all items | `Promise` | | `defineDriver(driver)` | Register custom driver | `Promise` | | `setEncryptionKey(key)` | Set encryption key (enterprise) | `void` | ``` -------------------------------- ### Initialize Encrypted Storage (Enterprise) Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/module-overview.md Setup for using Ionic Storage with encryption via the `@ionic-enterprise/secure-storage` driver. Requires defining the driver order and the encryption key. ```typescript import { Drivers } from '@ionic/storage'; import IonicSecureStorageDriver from '@ionic-enterprise/secure-storage/driver'; const storage = new Storage({ driverOrder: [Drivers.SecureStorage, Drivers.IndexedDB] }); await storage.defineDriver(IonicSecureStorageDriver); await storage.create(); storage.setEncryptionKey('key'); ``` -------------------------------- ### Ionic Storage Usage in a Component Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/ionic-storage-module.md Example demonstrating how to inject and use the Storage service within an Angular component's lifecycle. ```typescript import { Component } from '@angular/core'; import { Storage } from '@ionic/storage-angular'; @Component({ selector: 'app-root', templateUrl: 'app.component.html' }) export class AppComponent { constructor(private storage: Storage) {} async ngOnInit() { await this.storage.create(); await this.storage.set('user', { name: 'John' }); } } ``` -------------------------------- ### Storage Usage in Server-Side Rendering (Angular Universal) Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/module-overview.md Demonstrates using Ionic Storage in a server-side rendering context. Note that `get` operations will return `null` on the server. ```typescript // Same code works in browser and server context const storage = new Storage(); await storage.create(); const value = await storage.get('key'); // Returns null on server, real value in browser ``` -------------------------------- ### Configuration Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/README.md Explains how to configure the Storage instance using the constructor, including options for name, version, size, and driver order. ```APIDOC ### Configuration All configuration is passed to the `Storage` constructor: ```typescript new Storage({ name?: string; version?: number; size?: number; storeName?: string; description?: string; driverOrder?: Driver[]; dbKey?: string; }) ``` See [Configuration Reference](configuration.md) for details on each option. ``` -------------------------------- ### create() Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/storage.md Initializes the storage database by creating a LocalForage instance and setting up the driver chain. Must be called before any storage operations. ```APIDOC ## create() ### Description Initializes the storage database by creating a LocalForage instance and setting up the driver chain. Must be called before any storage operations. ### Signature ```typescript async create(): Promise ``` ### Parameters No parameters. ### Returns `Promise` — Resolves with the initialized Storage instance. ### Throws May throw if the underlying driver setup fails (e.g., if LocalForage configuration is invalid). ### Example ```typescript const storage = new Storage(); await storage.create(); // Now ready for operations await storage.set('key', 'value'); ``` ``` -------------------------------- ### Ionic Storage Initialization Flow Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/module-overview.md Demonstrates the typical initialization process for the Ionic Storage module, including defining custom drivers and creating the storage instance. ```typescript // Example initialization flow import { Storage, Drivers } from '@ionic/storage'; import IonicSecureStorageDriver from '@ionic-enterprise/secure-storage/driver'; // Step 1: Create instance const storage = new Storage({ driverOrder: [Drivers.SecureStorage, Drivers.IndexedDB] }); // Step 2: Define custom drivers await storage.defineDriver(IonicSecureStorageDriver); // Step 3: Initialize database await storage.create(); // Step 4: Use methods await storage.set('key', 'value'); const value = await storage.get('key'); ``` -------------------------------- ### Basic Web Storage Configuration Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/configuration.md Configure a basic storage instance for web applications. Ensure to await the create() method before using storage. ```typescript import { Storage } from '@ionic/storage'; const storage = new Storage({ name: 'myapp_db', storeName: 'app_store' }); await storage.create(); ``` -------------------------------- ### Best Practice: Initialize Storage Once Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/errors.md Illustrates the recommended approach for initializing Ionic Storage once during application startup. This applies to various frameworks like React, Vue, Vanilla JS, and Angular. ```typescript // React/Vue/Vanilla JS const storage = new Storage(); await storage.create(); // Now safe to use storage methods // Angular (automatic via module) @NgModule({ imports: [IonicStorageModule.forRoot()] }) export class AppModule { } // In component/service constructor(private storage: Storage) { this.storage.create(); // Called once } ``` -------------------------------- ### Basic Key-Value Operations Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/examples.md Demonstrates how to initialize the storage, store a string, retrieve it, and then remove it. Ensure storage is created before use. ```typescript import { Storage } from '@ionic/storage'; // Initialize const storage = new Storage(); await storage.create(); // Store a string await storage.set('user_name', 'John Doe'); // Retrieve it const name = await storage.get('user_name'); console.log(name); // 'John Doe' // Remove it await storage.remove('user_name'); // Check if removed const removed = await storage.get('user_name'); console.log(removed); // null ``` -------------------------------- ### Initialize Storage with Defaults Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/storage.md Use this snippet for basic initialization of the Storage class without custom configuration. It utilizes default settings for database name, store name, and driver order. ```typescript import { Storage, Drivers } from '@ionic/storage'; // Basic initialization with defaults const storage = new Storage(); ``` -------------------------------- ### Get an Item from Storage Source: https://github.com/ionic-team/ionic-storage/blob/main/README.md Retrieve a value from storage using its associated key with the `get` method. Ensure the key exists before attempting retrieval. ```javascript const name = await storage.get('name'); ``` -------------------------------- ### Test Storage Initialization Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/migration-guide.md Verify that the storage is initialized correctly after upgrading. The `create()` method must be called, and you can check the selected driver. ```typescript const storage = new Storage(); await storage.create(); console.log('Driver:', storage.driver); // Check which driver is selected ``` -------------------------------- ### Configuring Storage with Driver Order Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/types.md Illustrates how to configure the Storage instance with a specific order of drivers using the driverOrder option. This allows for fallback mechanisms, trying preferred drivers first. ```typescript import { Drivers, Storage } from '@ionic/storage'; const storage = new Storage({ driverOrder: [ Drivers.SecureStorage, // Try secure storage first (if installed) Drivers.IndexedDB, // Fall back to IndexedDB Drivers.LocalStorage // Fall back to local storage ] }); ``` -------------------------------- ### Install Enterprise Secure Storage Driver Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/drivers.md Install the Secure Storage driver, which requires an Ionic Enterprise subscription. This driver provides 256-bit AES encryption for sensitive data on iOS and Android. ```bash npm install @ionic-enterprise/secure-storage ``` -------------------------------- ### Initialize Storage with Custom Configuration Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/storage.md Configure the Storage class with custom options, such as a specific database name and a preferred order of storage drivers. This allows for tailored storage behavior. ```typescript import { Storage, Drivers } from '@ionic/storage'; // Custom configuration with specific driver order const storage = new Storage({ name: 'myapp_db', driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage] }); ``` -------------------------------- ### Create and Initialize Storage Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/storage.md Call the create() method after instantiating the Storage class to initialize the storage database and set up the driver chain. This must be done before performing any storage operations. ```typescript const storage = new Storage(); await storage.create(); // Now ready for operations await storage.set('key', 'value'); ``` -------------------------------- ### get() Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/storage.md Retrieves the value associated with the given key from storage. If the key does not exist, it resolves with null. ```APIDOC ## get() ### Description Retrieves the value associated with the given key from storage. ### Method get ### Parameters #### Path Parameters - **key** (string) - Required - The key identifying the value to retrieve ### Response #### Success Response - **any** - Resolves with the value stored at the key, or `null` if the key does not exist ### Throws - **Error** - If `create()` has not been called yet (message: "Database not created. Must call create() first") ### Example ```typescript const storage = new Storage(); await storage.create(); const name = await storage.get('user_name'); if (name) { console.log('Stored name:', name); } else { console.log('No name found'); } ``` ``` -------------------------------- ### Configuration Flow Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/module-overview.md Outlines the steps involved in configuring Ionic Storage, from application object creation to driver-specific behavior. ```text Application creates Storage config object ↓ StorageConfig interface validation ↓ Constructor merges with defaults ↓ create() passes to LocalForage ↓ LocalForage applies to selected driver ↓ Driver-specific behavior (quotas, persistence, etc.) ``` -------------------------------- ### Update Ionic Storage Packages Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/migration-guide.md Install the latest versions of the core Ionic Storage library and the Angular integration package. ```bash npm install @ionic/storage@^4.0.0 npm install @ionic/storage-angular@^4.0.0 ``` -------------------------------- ### Configure Storage in React/Vue/Vanilla JS Source: https://github.com/ionic-team/ionic-storage/blob/main/README.md Initialize the Storage service with custom configuration options, such as database name and driver order, by passing an options object to the constructor. ```typescript const storage = new Storage({ name: '__mydb', driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage] }); ``` -------------------------------- ### Get Active Storage Driver Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/storage.md Retrieve the name of the currently active storage driver. Useful for debugging or conditional logic. ```typescript const storage = new Storage({ driverOrder: ['indexeddb', 'localstorage'] }); await storage.create(); const activeDriver = storage.driver; console.log(`Using driver: ${activeDriver}`); // e.g., "indexeddb" ``` -------------------------------- ### Initialize Multiple Storage Instances Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/examples.md Create and manage separate storage instances for different data purposes. Use Promise.all for concurrent initialization. ```typescript // Separate stores for different purposes const userStorage = new Storage({ name: 'user_data', storeName: 'users' }); const cacheStorage = new Storage({ name: 'app_cache', storeName: 'cache' }); await Promise.all([ userStorage.create(), cacheStorage.create() ]); // Use independently await userStorage.set('user_id', '123'); await cacheStorage.set('api_response', { data: [] }); ``` -------------------------------- ### Get All Keys from Storage Source: https://github.com/ionic-team/ionic-storage/blob/main/README.md Retrieve an array of all keys currently stored using the `keys` method. This can be helpful for managing stored data. ```javascript await storage.keys() ``` -------------------------------- ### Initialize Ionic Storage Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/README.md Configure and initialize the Ionic Storage with custom options. Specify parameters like database name, version, size, and driver order. ```typescript new Storage({ name: "_my_appdb", version: 1, size: 1024, storeName: "user_data", description: "my custom data store", driverOrder: ["indexedDB", "localStorage"] }) ``` -------------------------------- ### Drivers Reference Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/MANIFEST.md Information about the available storage drivers, including built-in options and how to implement custom drivers. ```APIDOC ## Drivers ### Description Reference for the storage drivers supported by Ionic Storage, including built-in options like SecureStorage, IndexedDB, LocalStorage, and custom driver integration. ### Built-in Drivers - **`SecureStorage`**: For secure storage on mobile platforms. - **`IndexedDB`**: Web-based database for browser environments. - **`LocalStorage`**: Simple key-value storage in browsers. ### Custom Drivers - **`CordovaSQLiteDriver`**: Example of a custom driver for SQLite integration. ### `drivers` Constant Object - **Description**: An object containing references to all available drivers. ### Driver Characteristics Table - **Description**: Compares drivers based on features, platform support, and performance. ### Installation and Configuration - **Description**: Instructions for installing and configuring specific drivers based on the target platform. ### Driver Selection and Fallback - **Description**: Explains how Ionic Storage selects a driver and the fallback mechanism when a preferred driver is unavailable. ### Platform-Specific Recommendations - **Description**: Guidance on choosing the best driver for different platforms (web, iOS, Android). ### Storage Quota Management - **Description**: Information on managing storage quotas for different drivers. ### Browser Support Matrix - **Description**: Details browser compatibility for each driver. ``` -------------------------------- ### Driver Verification and Logging Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/errors.md This pattern initializes storage and then verifies the active driver, logging information about its capabilities and limitations. Use this to inform users or developers about the storage medium being used. ```typescript async function initializeStorage() { const storage = new Storage({ name: 'myapp', driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage] }); await storage.create(); const driver = storage.driver; if (!driver) { throw new Error('No storage driver available'); } if (driver === 'localstorage') { console.warn('Using LocalStorage - limited to 5-10MB'); } else if (driver === 'indexeddb') { console.log('Using IndexedDB - 50MB+ available'); } return storage; } ``` -------------------------------- ### Browser Environment Lifecycle Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/module-overview.md Steps for initializing and using Ionic Storage in a browser environment, where data persists across sessions. ```text 1. Import Storage from @ionic/storage 2. Create new Storage(config) 3. await storage.create() 4. IndexedDB or LocalStorage initialized 5. Use storage methods 6. Data persists across sessions ``` -------------------------------- ### Test Code Example (Not for Usage) Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/README.md Illustrates code that is considered test code and not suitable for direct use as a usage pattern. This is shown for contrast. ```typescript // ✗ Test code (not in examples) describe('Storage', () => { it('should work', async () => { expect(true).toBe(true); }); }); ``` -------------------------------- ### Configure Ionic Secure Storage Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/configuration.md Set up Ionic Secure Storage for encrypted data storage. This requires installing the enterprise package and defining the driver. ```typescript import { Drivers } from '@ionic/storage'; 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(); // Set encryption key (required for data protection) storage.setEncryptionKey('user-encryption-key'); // All data is now encrypted on disk await storage.set('sensitive', { pin: '1234' }); ``` -------------------------------- ### Get Number of Stored Items Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/storage.md Use the length() method to retrieve the total count of key-value pairs in storage. Ensure create() has been called first. ```typescript const storage = new Storage(); await storage.create(); await storage.set('key1', 'value1'); await storage.set('key2', 'value2'); const count = await storage.length(); // Returns 2 ``` -------------------------------- ### Storage Configuration with Size Limit Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/configuration.md Configure storage with a specific size limit (e.g., 50MB) and define the order of drivers to use. ```typescript const storage = new Storage({ name: 'large_data_store', size: 1024 * 1024 * 50, // 50MB driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage] }); ``` -------------------------------- ### Get the Quantity of Stored Items Source: https://github.com/ionic-team/ionic-storage/blob/main/README.md The `length` method returns the total number of key-value pairs stored. This provides a quick count of stored data. ```javascript await storage.length() ``` -------------------------------- ### Storage Configuration Source: https://github.com/ionic-team/ionic-storage/blob/main/README.md The Storage engine can be configured during initialization with specific driver priorities and custom options passed to localForage. ```APIDOC ## Configuration ### Description Allows configuration of the Storage engine, including driver order and custom options. ### Usage **React/Vue/Vanilla JavaScript:** ```typescript const storage = new Storage({ name: '__mydb', driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage] }); ``` **Angular:** ```typescript import { Drivers, Storage } from '@ionic/storage'; import { IonicStorageModule } from '@ionic/storage-angular'; @NgModule({ //... imports: [ IonicStorageModule.forRoot({ name: '__mydb', driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage] }) ], //... }) export class AppModule { } ``` ### Options - **`name`** (string): The name of the database. - **`driverOrder`** (Array): An array specifying the order of storage drivers to use. ``` -------------------------------- ### Store and Retrieve Data with Ionic Storage Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/00-START-HERE.md Basic usage for setting and getting data using the Storage class. Ensure the storage is created before use. ```typescript import { Storage } from '@ionic/storage'; const storage = new Storage(); await storage.create(); await storage.set('key', 'value'); const value = await storage.get('key'); ``` -------------------------------- ### Example Usage of forEach with IteratorCallback Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/types.md Demonstrates how to use the forEach method with a custom IteratorCallback to log stored items and stop iteration after a certain count. ```typescript const storage = new Storage(); await storage.create(); // Log first 3 items then stop let count = 0; await storage.forEach((value, key, index) => { console.log(`[${index}] ${key} = ${JSON.stringify(value)}`); if (++count >= 3) { return false; // Stop iteration } }); ``` -------------------------------- ### Use SQLite Driver on Mobile Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/README.md Configures Ionic Storage to use the Cordova SQLite driver for mobile platforms. Requires installing `localforage-cordovasqlitedriver` and defining the driver. ```typescript import CordovaSQLiteDriver from 'localforage-cordovasqlitedriver'; const storage = new Storage({ driverOrder: [CordovaSQLiteDriver._driver, Drivers.IndexedDB] }); await storage.defineDriver(CordovaSQLiteDriver); await storage.create(); ``` -------------------------------- ### Storage Constructor Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/storage.md Creates a new Storage instance with the specified configuration options. This is the main entry point for using Ionic Storage. ```APIDOC ## Storage Constructor ### Description Creates a new Storage instance with the specified configuration options. This is the main entry point for using Ionic Storage. ### Signature ```typescript constructor(config?: StorageConfig): Storage ``` ### Parameters #### Path Parameters - **config** (StorageConfig) - Optional - Configuration object to customize storage behavior, driver selection, and localForage options. Defaults to `{name: '_ionicstorage', storeName: '_ionickv', dbKey: '_ionickey', driverOrder: [SecureStorage, IndexedDB, LocalStorage]}`. ### Returns A new `Storage` instance (not initialized until `create()` is called). ### Example ```typescript import { Storage, Drivers } from '@ionic/storage'; // Basic initialization with defaults const storage = new Storage(); // Custom configuration with specific driver order const storage = new Storage({ name: 'myapp_db', driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage] }); ``` ``` -------------------------------- ### Inject Storage in Angular Component Source: https://github.com/ionic-team/ionic-storage/blob/main/README.md Inject the Storage service into an Angular component and call the create() method in ngOnInit. This is a basic setup for component-level storage access. ```typescript import { Component } from '@angular/core'; import { Storage } from '@ionic/storage'; @Component({ selector: 'app-root', templateUrl: 'app.component.html' }) export class AppComponent { constructor(private storage: Storage) { } async ngOnInit() { // If using a custom driver: // await this.storage.defineDriver(MyCustomDriver) await this.storage.create(); } } ``` -------------------------------- ### JSON Serialization and Deserialization Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/helpers.md Provides methods to easily store and retrieve JSON objects. It handles the stringification before setting and parsing after getting to maintain data types. ```typescript export class JsonStorage { constructor(private storage: Storage) {} async setJson(key: string, value: any): Promise { await this.storage.set(key, JSON.stringify(value)); } async getJson(key: string): Promise { const json = await this.storage.get(key); return json ? JSON.parse(json) : null; } } ``` -------------------------------- ### Check and Adapt Behavior Based on Active Driver Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/drivers.md Demonstrates how to determine the currently active storage driver and adjust application logic accordingly, providing warnings for limited drivers like LocalStorage. ```typescript const storage = new Storage(); await storage.create(); const activeDriver = storage.driver; console.log('Using driver:', activeDriver); // 'indexeddb' | 'localstorage' | 'ionicSecureStorage' // Adapt behavior based on driver if (activeDriver === 'localstorage') { console.warn('Using LocalStorage - limited to 5-10MB'); } else if (activeDriver === 'indexeddb') { console.log('Using IndexedDB - 50MB+ available'); } ``` -------------------------------- ### Core Library Structure Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/module-overview.md Illustrates the directory structure of the core Ionic Storage library, including the main JavaScript/Vue/React code, Angular-specific integration, and example applications. ```tree ionic-storage/ ├── lib/ # Main library (JavaScript/Vue/React) │ ├── src/ │ │ └── index.ts # Core Storage class │ ├── package.json # @ionic/storage package │ └── dist/ # Compiled output (multiple formats) │ ├── angular/ # Angular-specific integration │ ├── src/ │ │ └── index.ts # IonicStorageModule and Angular helpers │ ├── package.json # @ionic/storage-angular package │ └── dist/ # Compiled output │ └── examples/ # Example applications └── angular/ # Angular example app ``` -------------------------------- ### Batch Operations for Storage Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/helpers.md Facilitates performing multiple storage operations (set, get, remove) concurrently. This can improve performance by reducing the number of individual I/O operations. ```typescript export class BatchStorage { constructor(private storage: Storage) {} async setMany(items: Record): Promise { const promises = Object.entries(items).map(([key, value]) => this.storage.set(key, value) ); await Promise.all(promises); } async getMany(keys: string[]): Promise> { const promises = keys.map(key => this.storage.get(key)); const values = await Promise.all(promises); return keys.reduce((acc, key, i) => { acc[key] = values[i]; return acc; }, {} as Record); } async removeMany(keys: string[]): Promise { const promises = keys.map(key => this.storage.remove(key)); await Promise.all(promises); } } ``` -------------------------------- ### Mobile Environment Lifecycle (Capacitor) Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/module-overview.md Instructions for setting up and using Ionic Storage in a mobile application via Capacitor, with options for SQLite. ```text 1. Import Storage from @ionic/storage 2. Define custom SQLite driver (if needed) 3. Create new Storage(config) 4. await storage.create() 5. IndexedDB or SQLite initialized 6. Use storage methods 7. Data persists in app directory ``` -------------------------------- ### Get All Stored Keys Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/storage.md Use the keys() method to retrieve an array of all keys currently stored. The order of keys is preserved from insertion. Ensure create() has been called first. ```typescript const storage = new Storage(); await storage.create(); await storage.set('name', 'John'); await storage.set('email', 'john@example.com'); const allKeys = await storage.keys(); // ['name', 'email'] ``` -------------------------------- ### Create Multiple Storage Instances Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/helpers.md Use this pattern to create separate, independently configured Storage instances for different purposes within your application. Ensure to call `create()` on each instance before use. ```typescript // Separate stores for different purposes export class StorageConfig { static createUserStorage(): Storage { return new Storage({ name: 'user_store', storeName: 'users', driverOrder: [Drivers.SecureStorage, Drivers.IndexedDB] }); } static createCacheStorage(): Storage { return new Storage({ name: 'cache_store', storeName: 'cache', driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage] }); } } // Usage const userStorage = StorageConfig.createUserStorage(); const cacheStorage = StorageConfig.createCacheStorage(); await Promise.all([ userStorage.create(), cacheStorage.create() ]); ``` -------------------------------- ### Enterprise Encrypted Storage Configuration Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/configuration.md Configure secure storage for enterprise applications using a dedicated secure storage driver. A database key and encryption key are required for this setup. ```typescript import { Drivers } from '@ionic/storage'; import IonicSecureStorageDriver from '@ionic-enterprise/secure-storage/driver'; const storage = new Storage({ name: 'secure_vault', driverOrder: [Drivers.SecureStorage, Drivers.IndexedDB, Drivers.LocalStorage], dbKey: '_enterprise_key' }); await storage.defineDriver(IonicSecureStorageDriver); await storage.create(); storage.setEncryptionKey(userEncryptionKey); ``` -------------------------------- ### Retrieve Data from Storage Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/storage.md Use `get()` to retrieve a value associated with a specific key. Ensure `create()` has been called first. Resolves with the value or null if the key doesn't exist. ```typescript const storage = new Storage(); await storage.create(); const name = await storage.get('user_name'); if (name) { console.log('Stored name:', name); } else { console.log('No name found'); } ``` -------------------------------- ### Injecting StorageConfigToken in Angular Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/ionic-storage-module.md This example shows how to inject the StorageConfigToken in an Angular component using the @Inject decorator. This allows access to the storage configuration within custom services or factories. ```typescript import { Component, Inject } from '@angular/core'; import { StorageConfigToken } from '@ionic/storage-angular'; @Component({ selector: 'app-config-display' }) export class ConfigDisplayComponent { constructor(@Inject(StorageConfigToken) config: any) { console.log('Storage config:', config); } } ``` -------------------------------- ### Centralized Storage Service Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/helpers.md A recommended pattern for centralizing all storage operations in an Angular application. This service handles initialization and provides methods for setting, getting, and clearing user data and cache. ```typescript import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage-angular'; @Injectable({ providedIn: 'root' }) export class AppStorageService { private initialized = false; constructor(private storage: Storage) { this.init(); } async init(): Promise { if (!this.initialized) { await this.storage.create(); this.initialized = true; } } async setUser(user: any): Promise { await this.init(); await this.storage.set('user', user); } async getUser(): Promise { await this.init(); return this.storage.get('user'); } async clearUser(): Promise { await this.init(); await this.storage.remove('user'); } async setCacheData(key: string, data: any): Promise { await this.init(); await this.storage.set(`cache_${key}`, { data, timestamp: Date.now() }); } async getCacheData(key: string, maxAge?: number): Promise { await this.init(); const cached = await this.storage.get(`cache_${key}`); if (!cached) { return null; } if (maxAge && Date.now() - cached.timestamp > maxAge) { await this.storage.remove(`cache_${key}`); return null; } return cached.data; } async clear(): Promise { await this.init(); await this.storage.clear(); } } ``` -------------------------------- ### Basic Component Usage of Ionic Storage Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/examples.md Demonstrates how to inject and use the Storage service directly within an Angular component to get and set data. Ensure the storage is created before use. ```typescript import { Component } from '@angular/core'; import { Storage } from '@ionic/storage-angular'; @Component({ selector: 'app-settings', template: `

Current theme: {{ theme }}

` }) export class SettingsComponent { theme = 'light'; constructor(private storage: Storage) {} async ngOnInit() { await this.storage.create(); const saved = await this.storage.get('theme'); if (saved) { this.theme = saved; } } async saveTheme() { await this.storage.set('theme', this.theme); } } ``` -------------------------------- ### Configure Storage with Custom Driver Order Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/examples.md Specify the preferred order of storage drivers for web-only applications. Ensure the Storage driver is imported. ```typescript import { Drivers } from '@ionic/storage'; // For web-only applications const storage = new Storage({ name: 'web_app_storage', driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage] }); await storage.create(); ``` -------------------------------- ### Call create() Before Using Storage Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/migration-guide.md Ensure that the `create()` method is called on the Storage instance before attempting to use storage methods like `set()` to avoid 'Database not created' errors. ```typescript const storage = new Storage(); await storage.create(); // Call before using await storage.set('key', 'value'); ``` -------------------------------- ### Safe Data Access in Angular SSR Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/errors.md Ionic Storage provides a no-op implementation in SSR, returning null for get() and ignoring set/remove/clear operations. This prevents errors during server rendering. ```typescript // Safe in both browser and SSR context const value = await this.storage.get('key'); // null on server, actual value in browser if (value) { // This block only runs in browser } ``` -------------------------------- ### Project Structure Overview Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/00-START-HERE.md This snippet shows the directory structure of the Ionic Storage documentation. It helps in understanding the organization of different markdown files and API reference directories. ```text output/ ├── 00-START-HERE.md (this file) ├── README.md (master index) ├── module-overview.md ├── configuration.md ├── types.md ├── errors.md ├── examples.md ├── migration-guide.md ├── MANIFEST.md └── api-reference/ ├── storage.md ├── ionic-storage-module.md ├── drivers.md └── helpers.md ``` -------------------------------- ### Multiple Storage Instances Configuration Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/configuration.md Create and configure multiple independent storage instances for different data types or purposes within the same application. Each instance can have its own configuration. ```typescript // User data store const userStorage = new Storage({ name: 'user_data_store', storeName: 'users' }); // Cache store (with shorter retention) const cacheStorage = new Storage({ name: 'cache_store', storeName: 'cache' }); await userStorage.create(); await cacheStorage.create(); await userStorage.set('user_id', '12345'); await cacheStorage.set('api_response', { /* data */ }); ``` -------------------------------- ### Handle Storage Quota Exceeded Error Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/drivers.md Handles 'QuotaExceededError' when attempting to store data that exceeds the available storage limit. This example demonstrates clearing existing data and retrying the storage operation. ```typescript try { await storage.set('largeData', hugeObject); } catch (error) { if (error.name === 'QuotaExceededError') { console.error('Storage quota exceeded'); // Clear old data and retry await storage.clear(); await storage.set('largeData', hugeObject); } } ``` -------------------------------- ### setEncryptionKey(key: string) Source: https://github.com/ionic-team/ionic-storage/blob/main/_autodocs/api-reference/storage.md Sets the encryption key for use with Ionic Secure Storage (enterprise feature). This method must only be used when the Secure Storage driver is installed and configured to enable data encryption. ```APIDOC ## setEncryptionKey(key: string) ### Description Sets the encryption key for use with Ionic Secure Storage (enterprise feature). Must only be used when the Secure Storage driver is installed and configured. ### Method Signature `setEncryptionKey(key: string): void` ### Parameters - **key** (string) - Required - The encryption key string to use for securing stored data ### Example Usage ```typescript import { Drivers } from '@ionic/storage'; 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(); // Set encryption key storage.setEncryptionKey('my-secret-key-123'); // Now all data operations are encrypted await storage.set('sensitive_data', { ssn: '123-45-6789' }); ``` ### Returns `void` - This method does not return any value upon successful execution. ### Throws - **Error** - If Ionic Secure Storage is not installed (message: "@ionic-enterprise/secure-storage not installed. Encryption support not available") ```