Skip to main content

Secure Storage - Key Value API

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 KeyValueStorage utility class which provides a generic storage API, abstracting away storage engine details and providing a simple API with low overhead. Support for encryption is available when running on iOS and Android only.

Installation

npm install @ionic-enterprise/secure-storage

Usage

With React, Vue, Vanilla JavaScript

import { KeyValueStorage } from '@ionic-enterprise/secure-storage';

const storage = new KeyValueStorage();

await storage.create('key');

await storage.set('name', 'Mr. Ionitron');

With Angular

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 KeyValueStorage as a provider:

import { KeyValueStorage } from '@ionic-enterprise/secure-storage/ngx';

@NgModule({
declarations: [
...
],
providers: [
...,
KeyValueStorage
],
imports: [
...
],
// ...
})
export class AppModule { }

Next, register KeyValueStorage in your component and provide an encryption key (view recommendations for obtaining and securing an encryption key here) and initialize the storage engine by calling create('YOUR_ENCRYPTION_KEY_HERE'). Once encryption has been enabled, all saved data will automatically be encrypted.

  import { Component, OnInit } from '@angular/core';
import { KeyValueStorage } from '@ionic-enterprise/secure-storage/ngx';

@Component({
...
})
export class MyPage implements OnInit {
constructor(private storage: KeyValueStorage) { }

async ngOnInit() {
await this.storage.create('key');
}

async setIt() {
await this.storage.set('name', 'Mr. Ionitron');
}

async getIt() {
const name = await this.storage.get('name');
console.log(name);
}
}

Should you ever lose or forget the key used in create() you can destroy the KeyValueStorage so you can start clean via the destroyStorage() function:


...
// Angular
await this.storage.destroyStorage();


// React, Vue, Vanilla
await storage.destroyStorage();
...