CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-localforage

Fast and simple storage library for JavaScript with localStorage-like API that uses asynchronous storage (IndexedDB or WebSQL).

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

configuration.mddocs/

Configuration

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.

Capabilities

Configure Storage Options

Sets and persists localForage options. Configuration must be called before other operations and settings persist across driver changes.

/**
 * Sets configuration options
 * @param options - Configuration object with storage settings
 * @returns Boolean indicating success
 */
function config(options: LocalForageOptions): boolean;

/**
 * Gets a specific configuration value
 * @param options - Configuration key name
 * @returns The value of the specified configuration option
 */
function config(options: string): any;

/**
 * Gets all current configuration options
 * @returns Current configuration object
 */
function config(): LocalForageOptions;

Usage Examples:

import localforage from 'localforage';

// Set configuration options
localforage.config({
  driver: localforage.INDEXEDDB, // Force IndexedDB usage
  name: 'MyApp',
  version: 1.0,
  size: 4980736, // Size in bytes (~5MB)
  storeName: 'keyvaluepairs', // Table name
  description: 'My application storage'
});

// Get all configuration
const currentConfig = localforage.config();
console.log('Current config:', currentConfig);

// Get specific configuration value
const driverName = localforage.config('driver');
const dbName = localforage.config('name');

// Configuration with multiple drivers as fallbacks
localforage.config({
  driver: [
    localforage.INDEXEDDB,
    localforage.WEBSQL,
    localforage.LOCALSTORAGE
  ],
  name: 'MyAppData'
});

Set Storage Driver

Forces usage of specific storage driver(s) in order of preference. localForage will use the first available driver from the list.

/**
 * Sets the storage driver(s) to use
 * @param driver - Driver name or array of driver names in preference order
 * @param callback - Optional success callback
 * @param errorCallback - Optional error callback
 * @returns Promise resolving when driver is set
 */
function setDriver(
  driver: string | string[],
  callback?: () => void,
  errorCallback?: (error: any) => void
): Promise<void>;

Usage Examples:

import localforage from 'localforage';

// Force IndexedDB usage only
await localforage.setDriver(localforage.INDEXEDDB);

// Set driver preference order (fallback chain)
await localforage.setDriver([
  localforage.INDEXEDDB,   // Try IndexedDB first
  localforage.WEBSQL,      // Then WebSQL if IndexedDB unavailable
  localforage.LOCALSTORAGE // Finally localStorage as last resort
]);

// Using callbacks
localforage.setDriver(localforage.INDEXEDDB, 
  () => {
    console.log('IndexedDB driver successfully set');
  },
  (error) => {
    console.error('Failed to set IndexedDB driver:', error);
  }
);

// Check current driver after setting
await localforage.setDriver(localforage.WEBSQL);
console.log('Current driver:', localforage.driver()); // 'webSQLStorage'

// Handle driver setup errors
try {
  await localforage.setDriver('unsupportedDriver');
} catch (error) {
  console.error('Driver not supported:', error);
  // Fallback to default drivers
  await localforage.setDriver([
    localforage.INDEXEDDB,
    localforage.LOCALSTORAGE
  ]);
}

Create Storage Instance

Creates a new localForage instance with independent configuration and storage space. Each instance can have different settings and stores data separately.

/**
 * Creates a new localForage instance
 * @param options - Configuration options for the new instance
 * @returns New LocalForage instance
 */
function createInstance(options: LocalForageOptions): LocalForage;

Usage Examples:

import localforage from 'localforage';

// Create a user-specific storage instance
const userStore = localforage.createInstance({
  name: 'UserData',
  storeName: 'users'
});

// Create a cache storage instance
const cacheStore = localforage.createInstance({
  name: 'AppCache',
  storeName: 'cache',
  driver: localforage.LOCALSTORAGE // Use localStorage for cache
});

// Create a temporary storage instance
const tempStore = localforage.createInstance({
  name: 'TempData',
  storeName: 'temporary',
  description: 'Temporary application data'
});

// Each instance operates independently
await userStore.setItem('currentUser', { id: 1, name: 'Alice' });
await cacheStore.setItem('apiResponse', { data: [1, 2, 3] });
await tempStore.setItem('uploadProgress', 75);

// Different instances don't interfere with each other
const userData = await userStore.getItem('currentUser');
const cacheData = await cacheStore.getItem('apiResponse');

// Instances can have different drivers
const idbStore = localforage.createInstance({
  name: 'IndexedDBStore',
  driver: localforage.INDEXEDDB
});

const lsStore = localforage.createInstance({
  name: 'LocalStorageStore', 
  driver: localforage.LOCALSTORAGE
});

Drop Database Instance

Drops a database instance, removing all data and the database itself. This is a destructive operation that cannot be undone.

/**
 * Drops a database instance, removing all data
 * @param dbInstanceOptions - Optional database instance options to specify which instance to drop
 * @param callback - Optional callback function
 * @returns Promise resolving when the instance is dropped
 */
function dropInstance(dbInstanceOptions?: LocalForageDbInstanceOptions, callback?: (err: any) => void): Promise<void>;

Usage Examples:

import localforage from 'localforage';

// Drop the current default instance (removes all data)
await localforage.dropInstance();
console.log('Default database instance dropped');

// Drop a specific database by name
await localforage.dropInstance({
  name: 'MyAppData'
});

// Drop a specific store within a database
await localforage.dropInstance({
  name: 'MyAppData',
  storeName: 'cache'
});

// Drop instance with callbacks
localforage.dropInstance({
  name: 'TempData'
}, (err) => {
  if (err) {
    console.error('Failed to drop instance:', err);
  } else {
    console.log('Instance dropped successfully');
  }
});

// Drop instances created with createInstance
const userStore = localforage.createInstance({
  name: 'UserData',
  storeName: 'profiles'
});

// Use the instance and then drop it
await userStore.setItem('user1', { name: 'Alice' });
await userStore.dropInstance(); // Drops the UserData database

Configuration Options

interface LocalForageOptions {
  /**
   * Driver(s) to use, in order of preference
   * Can be a single driver or array of drivers
   */
  driver?: string | string[];
  
  /**
   * Database name - groups related storage instances
   */
  name?: string;
  
  /**
   * Store name - equivalent to table name in databases
   */
  storeName?: string;
  
  /**
   * Database size in bytes (primarily for WebSQL)
   */
  size?: number;
  
  /**
   * Database version number
   */
  version?: number;
  
  /**
   * Human-readable description of the database
   */
  description?: string;
}

interface LocalForageDbInstanceOptions {
  /**
   * Database name for instance-specific operations
   */
  name?: string;
  
  /**
   * Store name for instance-specific operations  
   */
  storeName?: string;
}

Default Configuration

// These are the default values used by localForage
const defaultConfig = {
  driver: [
    localforage.INDEXEDDB,    // 'asyncStorage'
    localforage.WEBSQL,       // 'webSQLStorage' 
    localforage.LOCALSTORAGE  // 'localStorageWrapper'
  ],
  name: 'localforage',
  storeName: 'keyvaluepairs',
  size: 4980736, // ~5MB
  version: 1.0,
  description: ''
};

Advanced Configuration Patterns

Application-Specific Storage Structure

import localforage from 'localforage';

// Create organized storage instances for different data types
const appStorage = {
  user: localforage.createInstance({
    name: 'MyApp',
    storeName: 'userData',
    description: 'User profiles and preferences'
  }),
  
  cache: localforage.createInstance({
    name: 'MyApp', 
    storeName: 'cache',
    driver: localforage.LOCALSTORAGE, // Use localStorage for cache
    description: 'Application cache data'
  }),
  
  files: localforage.createInstance({
    name: 'MyApp',
    storeName: 'files', 
    driver: localforage.INDEXEDDB, // Force IndexedDB for file storage
    description: 'User uploaded files and documents'
  })
};

// Use the organized storage
await appStorage.user.setItem('profile', userProfile);
await appStorage.cache.setItem('apiResponse', response);
await appStorage.files.setItem('document1', fileBlob);

Environment-Specific Configuration

// Configure based on environment capabilities
function configureStorage() {
  if (typeof window !== 'undefined') {
    // Browser environment
    localforage.config({
      driver: [
        localforage.INDEXEDDB,
        localforage.WEBSQL,
        localforage.LOCALSTORAGE
      ],
      name: 'WebApp'
    });
  } else {
    // Node.js or other environment - would need custom drivers
    console.warn('localForage primarily designed for browser environments');
  }
}

configureStorage();

Multi-Tenant Storage

// Create tenant-specific storage instances
function createTenantStorage(tenantId) {
  return {
    data: localforage.createInstance({
      name: `Tenant_${tenantId}`,
      storeName: 'data'
    }),
    
    settings: localforage.createInstance({
      name: `Tenant_${tenantId}`,
      storeName: 'settings' 
    }),
    
    cache: localforage.createInstance({
      name: `Tenant_${tenantId}`,
      storeName: 'cache',
      driver: localforage.LOCALSTORAGE
    })
  };
}

// Usage
const tenant1Storage = createTenantStorage('company-a');
const tenant2Storage = createTenantStorage('company-b');

await tenant1Storage.data.setItem('records', companyAData);
await tenant2Storage.data.setItem('records', companyBData);

Configuration Best Practices

  1. Set configuration early: Call config() before any storage operations
  2. Use specific names: Give meaningful names to databases and stores
  3. Plan driver fallbacks: Specify driver preferences based on your use case
  4. Separate concerns: Use different instances for different types of data
  5. Consider size limits: Be aware of storage quotas in different drivers
// Good configuration practice
localforage.config({
  name: 'MyApp_v2',           // Versioned database name
  storeName: 'userPreferences', // Descriptive store name
  driver: [                   // Ordered fallbacks
    localforage.INDEXEDDB,    // Best for large data
    localforage.LOCALSTORAGE  // Most compatible fallback
  ],
  size: 10485760,            // 10MB limit
  description: 'User preferences and settings for MyApp version 2'
});

docs

configuration.md

driver-development.md

index.md

storage-inspection.md

storage-operations.md

tile.json