Secure Storage - Ionic Storage
While Ionic Secure Storage provides a powerful SQLite-backed data store, it also has support for key/value functionality for simpler use cases or when data will fit in memory and querying can be done in JavaScript.
Key/value support is provided by the companion @ionic/storage
utility which provides a generic storage API that works across multiple platforms, abstracting away storage engine details and providing a simple API with low overhead. Support for encryption and sqlite is available when running on iOS and Android and using the Ionic Secure Storage driver for @ionic/storage
.
#
InstallationFirst, our app must have @ionic/storage installed. To do this, refer to the installation instructions for Ionic Storage.
Next, ensure that Secure Storage is installed:
npm install @ionic-enterprise/secure-storage
#
Usage#
With React, Vue, Vanilla JavaScriptimport { Drivers } from '@ionic/storage';import IonicSecureStorageDriver from '@ionic-enterprise/secure-storage/driver';
const store = new Storage({ driverOrder: [Drivers.SecureStorage, Drivers.IndexedDB, Drivers.LocalStorage]});
await store.defineDriver(IonicSecureStorageDriver);
#
With AngularUsage in Angular using Services and Dependency Injection requires importing the IonicStorageModule
and then injecting the Storage
class.
First, edit your NgModule declaration in src/app/app.module.ts
or in the module for the page you'll use the storage library in, and add IonicStorageModule
as an import:
import { Drivers } from '@ionic/storage';import { IonicStorageModule } from '@ionic/storage-angular';
@NgModule({ declarations: [ ... ], imports: [ IonicStorageModule.forRoot({ driverOrder: [Drivers.SecureStorage, Drivers.IndexedDB, Drivers.LocalStorage] }) ], // ...})export class AppModule { }
Next, register the Secure Storage driver in your component and provide an encryption key (view recommendations for obtaining and securing an encryption key here). Finally, initialize the storage engine by calling create()
.
async ngOnInit() { await this.storage.defineDriver(IonicSecureStorageDriver); await this.storage.setEncryptionKey("key"); await this.storage.create(); }
Once encryption has been enabled, all saved data will automatically be encrypted:
await storage.set('name', 'Mr. Ionitron');