localstorage-slim

repository·master·Indexed 40 days ago

https://github.com/digitalfortress-tech/localstorage-slim

An ultra-lightweight (approx. 1kB) JavaScript wrapper for the Web Storage API featuring Time-To-Live (TTL) for data expiration and optional encryption/obfuscation. Version 2.7.1 provides a zero-dependency solution to extend localStorage or sessionStorage with custom encryption logic and automatic MemoryStorage fallback.

Tokens
3.6K
Snippets
12
Records
13
Agent score
50%

What's inside localstorage-slim

  1. Handle localStorage fallback behavior

    master

    If the browser does not support localStorage, localstorage-slim automatically falls back to MemoryStorage.

    Implications:

    • Single Page Applications (SPAs): The fallback works perfectly as data persists for the duration of the session.
    • Multi-Page Applications (MPAs): Data will not be persisted between page loads/refreshes because MemoryStorage is volatile.
  2. Implement custom encryption and decryption

    master

    The default encryption is a simple obfuscation. For real security, you can override ls.config.encrypter and ls.config.decrypter with your own logic (e.g., using CryptoJS for AES). You can also provide a specific secret for individual items during set or get calls.

    // Example: Integrating a custom encryption algorithm
    ls.config.encrypt = true;
    ls.config.secret = 'my-secure-password';
    
    ls.config.encrypter = (data, secret) => {
      // Your encryption logic here
      return 'encrypted string';
    };
    
    ls.config.decrypter = (encryptedString, secret) => {
      // Your decryption logic here
      return 'original data';
    };
    
    // Using a specific secret for a single item
    ls.set('key', 'value', { secret: 'xyz' });
    ls.get('key', { secret: 'xyz' });
  3. Install localstorage-slim

    master

    You can install localstorage-slim via npm or Yarn. After installation, you can import it as an ES6 module, a CommonJS module, or include it via a <script> tag in the browser. When included via a script tag, the library is available globally as window.ls.

    # npm
    $ npm install --save localstorage-slim
    
    # yarn
    $ yarn add localstorage-slim
    // ES6 modules
    import ls from 'localstorage-slim';
    
    // CommonJS modules
    var ls = require('localstorage-slim');
    <!-- CDN via jsdelivr -->
    <script src="https://cdn.jsdelivr.net/npm/localstorage-slim"></script>
    
    <!-- CDN via unpkg -->
    <script src="https://unpkg.com/localstorage-slim@2.7.0/dist/localstorage-slim.js"></script>
  4. Use sessionStorage or a custom storage engine

    master

    By default, the library uses localStorage. You can switch to sessionStorage or any custom object that implements the Web Storage API by assigning it to ls.config.storage.

    /* Use sessionStorage */
    ls.config.storage = sessionStorage;
    
    /* Use a custom store */
    ls.config.storage = (() => {
      const store = {
        // implementation of getItem, setItem, removeItem, clear, length
      };
      return store;
    })();
  5. Configure localstorage-slim via ls.config

    master

    The ls.config object allows you to set global defaults for the library. All parameters are optional. Setting these will apply to all subsequent ls.set() and ls.get() calls unless overridden at the method level.

    ls.config.ttl = 3600; // Global TTL of 1 hour
    ls.config.encrypt = true; // Enable global encryption
    ls.config.secret = 'my-secret-key'; // Global secret for encryption
    ls.config.storage = sessionStorage; // Use sessionStorage instead of localStorage
  6. Basic usage of localstorage-slim

    master

    Use ls.set(key, value) to store data and ls.get(key) to retrieve it. The library supports various data types including objects, arrays, strings, and numbers. You can also provide an optional configuration object to set and get to specify ttl (Time To Live) in seconds or enable encrypt/decrypt for specific items.

    const value = { a: 1, b: 'test' };
    
    // Basic set and get
    ls.set('key1', value);
    ls.get('key1');
    
    // Using TTL (expiry in seconds)
    ls.set('key2', value, { ttl: 5 });
    ls.get('key2'); // returns value within 5 seconds
    // after 5 seconds, ls.get('key2') returns null
    
    // Using encryption for a specific item
    ls.set('key3', value, { encrypt: true });
    ls.get('key3', { decrypt: true });
  7. Use the localstorage-slim API

    master

    The localstorage-slim API is designed to be highly similar to the native LocalStorage API, providing methods to set, get, remove, and clear data. It extends the native functionality with support for TTL (Time To Live) and encryption.

    Core Methods

    • ls.set(key, value, config = {}): Stores a value. Supports ttl (seconds) and encrypt (boolean) via the config object.
    • ls.get(key, config = {}): Retrieves a value. If a TTL was set, it returns null if the item has expired. If the item was encrypted, pass { decrypt: true } in the config to retrieve the plain text.
    • ls.remove(key): Deletes the specific item associated with the key.
    • ls.clear(): Wipes all data from the linked storage.
    • ls.flush(force = false): Manually triggers the removal of expired items. If force is set to true, it removes all items that have a TTL, even if they haven't expired yet.
    // Setting values with TTL and encryption
    ls.set('key', 'value', { ttl: 5, encrypt: true });
    
    // Getting values
    const value = ls.get('key', { decrypt: true });
    
    // Removing specific items
    ls.remove('key');
    
    // Clearing everything
    ls.clear();
    
    // Flushing expired or all TTL-enabled items
    ls.flush(); // removes expired
    ls.flush(true); // removes all items with a TTL
  8. Configure localstorage-slim via StorageConfig

    master

    The StorageConfig interface defines the configuration options for initializing localstorage-slim. You can specify the storage engine, time-to-live (TTL), and encryption/decryption behavior.

    Key configuration properties:

    • storage: An instance of the Web Storage API (e.g., localStorage or sessionStorage).
    • ttl: A number representing the time-to-live in milliseconds. Set to null to disable.
    • encrypt: A boolean to enable encryption before saving data.
    • decrypt: A boolean to enable decryption when retrieving data.
    • encrypter: A custom function to handle encryption. It must accept any number of arguments and return a string.
    • decrypter: A custom function to handle decryption. It must accept any number of arguments and return the original data type (unknown).
    • secret: A value passed to the encrypter and decrypter functions.
    const config: StorageConfig = {
      storage: localStorage,
      ttl: 3600000, // 1 hour
      encrypt: true,
      decrypt: true,
      secret: 'my-secret-key',
      encrypter: (data, secret) => {
        // implementation returning a string
        return encryptedString;
      },
      decrypter: (encryptedData, secret) => {
        // implementation returning original data
        return originalData;
      }
    };
  9. Reference: ls.config parameters

    master

    The following parameters are available in the ls.config object to customize library behavior globally.

    | Parameter | Description | Default |
    | --------- | ----------- | ------- |
    | `ttl?: number|null` | Global TTL in seconds for every item stored. | `null` |
    | `encrypt?: boolean` | Enable global encryption of stored data. | `false` |
    | `decrypt?: boolean` | Used only by `ls.get()` to decrypt data. | `undefined` |
    | `encrypter?: (data: unknown, secret: string): string` | Custom encryption function. Default is obfuscation. | Obfuscation |
    | `decrypter?: (encryptedString: string, secret: string): unknown` | Custom decryption function. Default is deobfuscation. | deobfuscation |
    | `secret?: unknown` | Secret key passed to encrypter/decrypter. | (none) |
    | `storage?: Storage` | The Storage implementation to use (e.g., `localStorage`, `sessionStorage`). | `localStorage` |
  10. Define custom Encrypter and Decrypter functions

    master

    If you enable encryption in StorageConfig, you can provide custom logic via the encrypter and decrypter types to control how data is transformed.

    • Encrypter: A function signature (...args: unknown[]) => string. It is responsible for taking the data (and optionally a secret) and returning an encrypted string.
    • Decrypter: A function signature (...args: unknown[]) => unknown. It is responsible for taking the encrypted string (and optionally a secret) and returning the original value.
    type Encrypter = (...args: unknown[]) => string;
    type Decrypter = (...args: unknown[]) => unknown;
  11. Set items with ls.set()

    master

    Use ls.set(key, value, config) to store data.

    Arguments:

    1. key: string (Required): The identifier for the data.
    2. value: string|Date|Number|Object|Boolean|Null (Required): The data to store.
    3. config: Config (Optional): An object that accepts the same properties as the global config (except storage).

    Common Config Options:

    • ttl: Number of seconds until the item expires. This overrides the global ls.config.ttl if provided.
    • encrypt: Boolean. If true, the specific field will be encrypted.

    Returns false if there was an error, otherwise returns undefined.

    const res = ls.set('key', 'value');
    // returns undefined if successful or false if there was a problem
    
    // with ttl
    ls.config.ttl = 3;      // global ttl set to 3 seconds
    ls.set('key', 'value'); // value expires after 3s
    ls.set('key', 'value', { ttl: 5 }); // value expires after 5s (overrides global ttl)
    
    // with encryption
    ls.set('key', 'value', { encrypt: true });
  12. Flush expired items with ls.flush()

    master

    The ls.flush(force = false) method manages the removal of items based on their TTL.

    • ls.flush(): Removes only the items that have already expired.
    • ls.flush(true): Force-flushes all items that have a TTL set, even if they are not yet expired.

    Note: flush(true) only affects items that had a TTL set. To remove data without a TTL, use remove() or clear().

    // removes all expired data (i.e. ttl has expired)
    ls.flush();
    
    // removes all data that has a ttl (i.e. even if the ttl has not yet expired)
    ls.flush(true);