0
# Configuration
1
2
Configuration system for customizing storage behavior, driver selection, and creating multiple storage instances. localForage provides flexible configuration options to control database settings, driver preferences, and instance management.
3
4
## Capabilities
5
6
### Configure Storage Options
7
8
Sets and persists localForage options. Configuration must be called before other operations and settings persist across driver changes.
9
10
```javascript { .api }
11
/**
12
* Sets configuration options
13
* @param options - Configuration object with storage settings
14
* @returns Boolean indicating success
15
*/
16
function config(options: LocalForageOptions): boolean;
17
18
/**
19
* Gets a specific configuration value
20
* @param options - Configuration key name
21
* @returns The value of the specified configuration option
22
*/
23
function config(options: string): any;
24
25
/**
26
* Gets all current configuration options
27
* @returns Current configuration object
28
*/
29
function config(): LocalForageOptions;
30
```
31
32
**Usage Examples:**
33
34
```javascript
35
import localforage from 'localforage';
36
37
// Set configuration options
38
localforage.config({
39
driver: localforage.INDEXEDDB, // Force IndexedDB usage
40
name: 'MyApp',
41
version: 1.0,
42
size: 4980736, // Size in bytes (~5MB)
43
storeName: 'keyvaluepairs', // Table name
44
description: 'My application storage'
45
});
46
47
// Get all configuration
48
const currentConfig = localforage.config();
49
console.log('Current config:', currentConfig);
50
51
// Get specific configuration value
52
const driverName = localforage.config('driver');
53
const dbName = localforage.config('name');
54
55
// Configuration with multiple drivers as fallbacks
56
localforage.config({
57
driver: [
58
localforage.INDEXEDDB,
59
localforage.WEBSQL,
60
localforage.LOCALSTORAGE
61
],
62
name: 'MyAppData'
63
});
64
```
65
66
### Set Storage Driver
67
68
Forces usage of specific storage driver(s) in order of preference. localForage will use the first available driver from the list.
69
70
```javascript { .api }
71
/**
72
* Sets the storage driver(s) to use
73
* @param driver - Driver name or array of driver names in preference order
74
* @param callback - Optional success callback
75
* @param errorCallback - Optional error callback
76
* @returns Promise resolving when driver is set
77
*/
78
function setDriver(
79
driver: string | string[],
80
callback?: () => void,
81
errorCallback?: (error: any) => void
82
): Promise<void>;
83
```
84
85
**Usage Examples:**
86
87
```javascript
88
import localforage from 'localforage';
89
90
// Force IndexedDB usage only
91
await localforage.setDriver(localforage.INDEXEDDB);
92
93
// Set driver preference order (fallback chain)
94
await localforage.setDriver([
95
localforage.INDEXEDDB, // Try IndexedDB first
96
localforage.WEBSQL, // Then WebSQL if IndexedDB unavailable
97
localforage.LOCALSTORAGE // Finally localStorage as last resort
98
]);
99
100
// Using callbacks
101
localforage.setDriver(localforage.INDEXEDDB,
102
() => {
103
console.log('IndexedDB driver successfully set');
104
},
105
(error) => {
106
console.error('Failed to set IndexedDB driver:', error);
107
}
108
);
109
110
// Check current driver after setting
111
await localforage.setDriver(localforage.WEBSQL);
112
console.log('Current driver:', localforage.driver()); // 'webSQLStorage'
113
114
// Handle driver setup errors
115
try {
116
await localforage.setDriver('unsupportedDriver');
117
} catch (error) {
118
console.error('Driver not supported:', error);
119
// Fallback to default drivers
120
await localforage.setDriver([
121
localforage.INDEXEDDB,
122
localforage.LOCALSTORAGE
123
]);
124
}
125
```
126
127
### Create Storage Instance
128
129
Creates a new localForage instance with independent configuration and storage space. Each instance can have different settings and stores data separately.
130
131
```javascript { .api }
132
/**
133
* Creates a new localForage instance
134
* @param options - Configuration options for the new instance
135
* @returns New LocalForage instance
136
*/
137
function createInstance(options: LocalForageOptions): LocalForage;
138
```
139
140
**Usage Examples:**
141
142
```javascript
143
import localforage from 'localforage';
144
145
// Create a user-specific storage instance
146
const userStore = localforage.createInstance({
147
name: 'UserData',
148
storeName: 'users'
149
});
150
151
// Create a cache storage instance
152
const cacheStore = localforage.createInstance({
153
name: 'AppCache',
154
storeName: 'cache',
155
driver: localforage.LOCALSTORAGE // Use localStorage for cache
156
});
157
158
// Create a temporary storage instance
159
const tempStore = localforage.createInstance({
160
name: 'TempData',
161
storeName: 'temporary',
162
description: 'Temporary application data'
163
});
164
165
// Each instance operates independently
166
await userStore.setItem('currentUser', { id: 1, name: 'Alice' });
167
await cacheStore.setItem('apiResponse', { data: [1, 2, 3] });
168
await tempStore.setItem('uploadProgress', 75);
169
170
// Different instances don't interfere with each other
171
const userData = await userStore.getItem('currentUser');
172
const cacheData = await cacheStore.getItem('apiResponse');
173
174
// Instances can have different drivers
175
const idbStore = localforage.createInstance({
176
name: 'IndexedDBStore',
177
driver: localforage.INDEXEDDB
178
});
179
180
const lsStore = localforage.createInstance({
181
name: 'LocalStorageStore',
182
driver: localforage.LOCALSTORAGE
183
});
184
```
185
186
### Drop Database Instance
187
188
Drops a database instance, removing all data and the database itself. This is a destructive operation that cannot be undone.
189
190
```javascript { .api }
191
/**
192
* Drops a database instance, removing all data
193
* @param dbInstanceOptions - Optional database instance options to specify which instance to drop
194
* @param callback - Optional callback function
195
* @returns Promise resolving when the instance is dropped
196
*/
197
function dropInstance(dbInstanceOptions?: LocalForageDbInstanceOptions, callback?: (err: any) => void): Promise<void>;
198
```
199
200
**Usage Examples:**
201
202
```javascript
203
import localforage from 'localforage';
204
205
// Drop the current default instance (removes all data)
206
await localforage.dropInstance();
207
console.log('Default database instance dropped');
208
209
// Drop a specific database by name
210
await localforage.dropInstance({
211
name: 'MyAppData'
212
});
213
214
// Drop a specific store within a database
215
await localforage.dropInstance({
216
name: 'MyAppData',
217
storeName: 'cache'
218
});
219
220
// Drop instance with callbacks
221
localforage.dropInstance({
222
name: 'TempData'
223
}, (err) => {
224
if (err) {
225
console.error('Failed to drop instance:', err);
226
} else {
227
console.log('Instance dropped successfully');
228
}
229
});
230
231
// Drop instances created with createInstance
232
const userStore = localforage.createInstance({
233
name: 'UserData',
234
storeName: 'profiles'
235
});
236
237
// Use the instance and then drop it
238
await userStore.setItem('user1', { name: 'Alice' });
239
await userStore.dropInstance(); // Drops the UserData database
240
```
241
242
## Configuration Options
243
244
```javascript { .api }
245
interface LocalForageOptions {
246
/**
247
* Driver(s) to use, in order of preference
248
* Can be a single driver or array of drivers
249
*/
250
driver?: string | string[];
251
252
/**
253
* Database name - groups related storage instances
254
*/
255
name?: string;
256
257
/**
258
* Store name - equivalent to table name in databases
259
*/
260
storeName?: string;
261
262
/**
263
* Database size in bytes (primarily for WebSQL)
264
*/
265
size?: number;
266
267
/**
268
* Database version number
269
*/
270
version?: number;
271
272
/**
273
* Human-readable description of the database
274
*/
275
description?: string;
276
}
277
278
interface LocalForageDbInstanceOptions {
279
/**
280
* Database name for instance-specific operations
281
*/
282
name?: string;
283
284
/**
285
* Store name for instance-specific operations
286
*/
287
storeName?: string;
288
}
289
```
290
291
## Default Configuration
292
293
```javascript
294
// These are the default values used by localForage
295
const defaultConfig = {
296
driver: [
297
localforage.INDEXEDDB, // 'asyncStorage'
298
localforage.WEBSQL, // 'webSQLStorage'
299
localforage.LOCALSTORAGE // 'localStorageWrapper'
300
],
301
name: 'localforage',
302
storeName: 'keyvaluepairs',
303
size: 4980736, // ~5MB
304
version: 1.0,
305
description: ''
306
};
307
```
308
309
## Advanced Configuration Patterns
310
311
### Application-Specific Storage Structure
312
313
```javascript
314
import localforage from 'localforage';
315
316
// Create organized storage instances for different data types
317
const appStorage = {
318
user: localforage.createInstance({
319
name: 'MyApp',
320
storeName: 'userData',
321
description: 'User profiles and preferences'
322
}),
323
324
cache: localforage.createInstance({
325
name: 'MyApp',
326
storeName: 'cache',
327
driver: localforage.LOCALSTORAGE, // Use localStorage for cache
328
description: 'Application cache data'
329
}),
330
331
files: localforage.createInstance({
332
name: 'MyApp',
333
storeName: 'files',
334
driver: localforage.INDEXEDDB, // Force IndexedDB for file storage
335
description: 'User uploaded files and documents'
336
})
337
};
338
339
// Use the organized storage
340
await appStorage.user.setItem('profile', userProfile);
341
await appStorage.cache.setItem('apiResponse', response);
342
await appStorage.files.setItem('document1', fileBlob);
343
```
344
345
### Environment-Specific Configuration
346
347
```javascript
348
// Configure based on environment capabilities
349
function configureStorage() {
350
if (typeof window !== 'undefined') {
351
// Browser environment
352
localforage.config({
353
driver: [
354
localforage.INDEXEDDB,
355
localforage.WEBSQL,
356
localforage.LOCALSTORAGE
357
],
358
name: 'WebApp'
359
});
360
} else {
361
// Node.js or other environment - would need custom drivers
362
console.warn('localForage primarily designed for browser environments');
363
}
364
}
365
366
configureStorage();
367
```
368
369
### Multi-Tenant Storage
370
371
```javascript
372
// Create tenant-specific storage instances
373
function createTenantStorage(tenantId) {
374
return {
375
data: localforage.createInstance({
376
name: `Tenant_${tenantId}`,
377
storeName: 'data'
378
}),
379
380
settings: localforage.createInstance({
381
name: `Tenant_${tenantId}`,
382
storeName: 'settings'
383
}),
384
385
cache: localforage.createInstance({
386
name: `Tenant_${tenantId}`,
387
storeName: 'cache',
388
driver: localforage.LOCALSTORAGE
389
})
390
};
391
}
392
393
// Usage
394
const tenant1Storage = createTenantStorage('company-a');
395
const tenant2Storage = createTenantStorage('company-b');
396
397
await tenant1Storage.data.setItem('records', companyAData);
398
await tenant2Storage.data.setItem('records', companyBData);
399
```
400
401
## Configuration Best Practices
402
403
1. **Set configuration early**: Call `config()` before any storage operations
404
2. **Use specific names**: Give meaningful names to databases and stores
405
3. **Plan driver fallbacks**: Specify driver preferences based on your use case
406
4. **Separate concerns**: Use different instances for different types of data
407
5. **Consider size limits**: Be aware of storage quotas in different drivers
408
409
```javascript
410
// Good configuration practice
411
localforage.config({
412
name: 'MyApp_v2', // Versioned database name
413
storeName: 'userPreferences', // Descriptive store name
414
driver: [ // Ordered fallbacks
415
localforage.INDEXEDDB, // Best for large data
416
localforage.LOCALSTORAGE // Most compatible fallback
417
],
418
size: 10485760, // 10MB limit
419
description: 'User preferences and settings for MyApp version 2'
420
});
421
```