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.00
# Ionic Storage
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: @ionic/storage
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @ionic/storage`
10
11
For Angular applications, use the separate `@ionic/storage-angular` package instead:
12
```bash
13
npm install @ionic/storage-angular
14
```
15
16
## Core Imports
17
18
```typescript
19
import { Storage, Drivers, StorageConfig } from "@ionic/storage";
20
```
21
22
For CommonJS:
23
```javascript
24
const { Storage, Drivers } = require("@ionic/storage");
25
```
26
27
## Basic Usage
28
29
```typescript
30
import { Storage } from "@ionic/storage";
31
32
// Create and initialize storage
33
const storage = new Storage();
34
await storage.create();
35
36
// Basic operations
37
await storage.set('name', 'Mr. Ionitron');
38
const name = await storage.get('name');
39
await storage.remove('name');
40
await storage.clear();
41
42
// Information about stored data
43
const keys = await storage.keys();
44
const count = await storage.length();
45
46
// Iterate through all data
47
await storage.forEach((value, key, iterationNumber) => {
48
console.log(`${key}: ${value}`);
49
});
50
```
51
52
## Architecture
53
54
Ionic Storage is built around several key components:
55
56
- **Storage Class**: Main interface providing all key-value operations with Promise-based API
57
- **Driver System**: Pluggable storage backends with automatic selection and fallback support
58
- **Configuration System**: Flexible configuration for database names, driver priorities, and LocalForage options
59
- **Cross-Platform Support**: Seamless operation across web (IndexedDB/localStorage) and native platforms (SQLite)
60
- **Enterprise Features**: Optional encryption support through Ionic Secure Storage for security-sensitive applications
61
62
## Capabilities
63
64
### Storage Instance Creation
65
66
Create and configure a Storage instance with optional configuration.
67
68
```typescript { .api }
69
/**
70
* Create a new Storage instance using the order of drivers and any additional config
71
* options to pass to LocalForage.
72
*/
73
class Storage {
74
constructor(config?: StorageConfig);
75
}
76
77
interface StorageConfig {
78
/** Database name (default: '_ionicstorage') */
79
name?: string;
80
/** Database version */
81
version?: number;
82
/** Database size limit */
83
size?: number;
84
/** Store name within database (default: '_ionickv') */
85
storeName?: string;
86
/** Database description */
87
description?: string;
88
/** Array specifying driver priority order */
89
driverOrder?: Driver[];
90
/** Database key (default: '_ionickey') */
91
dbKey?: string;
92
}
93
```
94
95
### Database Initialization
96
97
Initialize the storage instance and set up drivers. Must be called before any data operations.
98
99
```typescript { .api }
100
/**
101
* Initialize the storage instance and set up drivers
102
* @returns Promise resolving to the Storage instance
103
*/
104
create(): Promise<Storage>;
105
```
106
107
**Usage Example:**
108
```typescript
109
const storage = new Storage({
110
name: 'myApp',
111
driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage]
112
});
113
await storage.create();
114
```
115
116
### Driver Management
117
118
Define custom storage drivers before initialization.
119
120
```typescript { .api }
121
/**
122
* Define a new Driver. Must be called before initializing the database.
123
* @param driver - Driver implementation to register
124
* @returns Promise from LocalForage.defineDriver
125
*/
126
defineDriver(driver: any): Promise<any>;
127
128
/**
129
* Get the name of the driver being used
130
* @returns Name of the current driver or null if not initialized
131
*/
132
get driver(): string | null;
133
```
134
135
**Usage Example:**
136
```typescript
137
import CordovaSQLiteDriver from 'localforage-cordovasqlitedriver';
138
139
const storage = new Storage({
140
driverOrder: [CordovaSQLiteDriver._driver, Drivers.IndexedDB]
141
});
142
143
await storage.defineDriver(CordovaSQLiteDriver);
144
await storage.create();
145
```
146
147
### Key-Value Operations
148
149
Core storage operations for setting, getting, and removing data.
150
151
```typescript { .api }
152
/**
153
* Get the value associated with the given key
154
* @param key - The key to identify this value
155
* @returns Promise with the value of the given key
156
*/
157
get(key: string): Promise<any>;
158
159
/**
160
* Set the value for the given key
161
* @param key - The key to identify this value
162
* @param value - The value for this key
163
* @returns Promise that resolves when the key and value are set
164
*/
165
set(key: string, value: any): Promise<any>;
166
167
/**
168
* Remove any value associated with this key
169
* @param key - The key to identify this value
170
* @returns Promise that resolves when the value is removed
171
*/
172
remove(key: string): Promise<any>;
173
174
/**
175
* Clear the entire key value store. WARNING: HOT!
176
* @returns Promise that resolves when the store is cleared
177
*/
178
clear(): Promise<void>;
179
```
180
181
**Usage Examples:**
182
```typescript
183
// Store different data types
184
await storage.set('user', { name: 'John', id: 123 });
185
await storage.set('settings', { theme: 'dark', notifications: true });
186
await storage.set('lastLogin', new Date().toISOString());
187
188
// Retrieve data
189
const user = await storage.get('user');
190
const theme = await storage.get('settings');
191
const lastLogin = await storage.get('lastLogin');
192
193
// Remove specific items
194
await storage.remove('user');
195
196
// Clear all data
197
await storage.clear();
198
```
199
200
### Storage Information
201
202
Methods to inspect and enumerate stored data.
203
204
```typescript { .api }
205
/**
206
* Get the number of keys stored
207
* @returns Promise that resolves with the number of keys stored
208
*/
209
length(): Promise<number>;
210
211
/**
212
* Get all stored keys
213
* @returns Promise that resolves with the keys in the store
214
*/
215
keys(): Promise<string[]>;
216
217
/**
218
* Iterate through each key,value pair
219
* @param iteratorCallback - Callback function called for each item
220
* @returns Promise that resolves when the iteration has finished
221
*/
222
forEach(
223
iteratorCallback: (value: any, key: string, iterationNumber: number) => any
224
): Promise<void>;
225
```
226
227
**Usage Examples:**
228
```typescript
229
// Check storage size
230
const count = await storage.length();
231
console.log(`Storage contains ${count} items`);
232
233
// List all keys
234
const allKeys = await storage.keys();
235
console.log('Stored keys:', allKeys);
236
237
// Process all stored data
238
await storage.forEach((value, key, iterationNumber) => {
239
console.log(`Item ${iterationNumber}: ${key} = ${JSON.stringify(value)}`);
240
});
241
```
242
243
### Encryption Support
244
245
Enable encryption when using Ionic Secure Storage driver (enterprise feature).
246
247
```typescript { .api }
248
/**
249
* Set encryption key for secure storage
250
* @param key - Encryption key string
251
* @throws Error if @ionic-enterprise/secure-storage not installed
252
*/
253
setEncryptionKey(key: string): void;
254
```
255
256
**Usage Example:**
257
```typescript
258
import IonicSecureStorageDriver from '@ionic-enterprise/secure-storage/driver';
259
260
const storage = new Storage({
261
driverOrder: [Drivers.SecureStorage, Drivers.IndexedDB, Drivers.LocalStorage]
262
});
263
264
await storage.defineDriver(IonicSecureStorageDriver);
265
await storage.create();
266
267
// Enable encryption
268
storage.setEncryptionKey('mySecretKey');
269
270
// All subsequent operations will be encrypted
271
await storage.set('sensitiveData', { token: 'abc123' });
272
```
273
274
## Driver Constants
275
276
Pre-defined driver identifiers for configuration.
277
278
```typescript { .api }
279
const Drivers = {
280
/** Ionic Secure Storage driver identifier (enterprise) */
281
SecureStorage: 'ionicSecureStorage',
282
/** IndexedDB driver identifier */
283
IndexedDB: 'asyncStorage',
284
/** LocalStorage driver identifier */
285
LocalStorage: 'localStorageWrapper'
286
};
287
```
288
289
## Types
290
291
```typescript { .api }
292
/**
293
* Database instance type (LocalForage compatible)
294
*/
295
type Database = any;
296
297
/**
298
* Driver type for storage engines
299
*/
300
type Driver = any;
301
```
302
303
## Error Handling
304
305
The Storage class throws specific errors for common failure scenarios:
306
307
- **Database not initialized**: Thrown when calling methods before `create()`
308
- **Secure storage not available**: Thrown when calling `setEncryptionKey()` without the enterprise driver
309
310
```typescript
311
try {
312
await storage.get('key');
313
} catch (error) {
314
if (error.message.includes('Database not created')) {
315
console.error('Storage not initialized. Call create() first.');
316
}
317
}
318
```
319
320
## Platform Support
321
322
- **Web**: IndexedDB (preferred), LocalStorage (fallback)
323
- **Capacitor/Cordova**: SQLite (with additional driver), IndexedDB, LocalStorage
324
- **Enterprise**: Ionic Secure Storage with 256-bit AES encryption
325
326
## Configuration Examples
327
328
### Basic Configuration
329
```typescript
330
const storage = new Storage({
331
name: 'myApp',
332
storeName: 'keyvaluepairs'
333
});
334
```
335
336
### Custom Driver Order
337
```typescript
338
const storage = new Storage({
339
name: 'myApp',
340
driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage]
341
});
342
```
343
344
### SQLite Support (Cordova/Capacitor)
345
```typescript
346
import CordovaSQLiteDriver from 'localforage-cordovasqlitedriver';
347
348
const storage = new Storage({
349
driverOrder: [CordovaSQLiteDriver._driver, Drivers.IndexedDB, Drivers.LocalStorage]
350
});
351
352
await storage.defineDriver(CordovaSQLiteDriver);
353
```
354
355
### Secure Storage (Enterprise)
356
```typescript
357
import IonicSecureStorageDriver from '@ionic-enterprise/secure-storage/driver';
358
359
const storage = new Storage({
360
driverOrder: [Drivers.SecureStorage, Drivers.IndexedDB, Drivers.LocalStorage]
361
});
362
363
await storage.defineDriver(IonicSecureStorageDriver);
364
await storage.create();
365
storage.setEncryptionKey('your-encryption-key');
366
```