### TypeScript Type-Safe Get and Configuration Example
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/INDEX.md
Demonstrates how to use the localstorage-slim library with TypeScript for type-safe data retrieval and configuration. It shows defining a type for retrieved data and applying a configuration object.
```typescript
import type { StorageConfig } from 'localstorage-slim';
import ls from 'localstorage-slim';
// Type-safe get
const user = ls.get<{ id: number; name: string }>('user');
// Type-safe config
const config: StorageConfig = {
ttl: 300,
encrypt: true,
secret: 'password'
};
// Apply config
Object.assign(ls.config, config);
```
--------------------------------
### Storage Interface Implementation Examples
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/types.md
Provides examples of how to configure the library to use different storage mechanisms, including the browser's built-in `sessionStorage`, `localStorage`, and a custom in-memory object that mimics the Storage interface.
```javascript
// Use sessionStorage
ls.config.storage = sessionStorage;
// Use a custom in-memory store
ls.config.storage = {
length: 0,
clear() { /* ... */ },
getItem(key) { /* ... */ },
key(index) { /* ... */ },
removeItem(key) { /* ... */ },
setItem(key, value) { /* ... */ }
};
// Use localStorage explicitly
ls.config.storage = localStorage;
```
--------------------------------
### Install localstorage-slim with npm or Yarn
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/README.md
Install the library using npm or Yarn. This is the first step before including it in your project.
```shell
$ npm install --save localstorage-slim
# Alternatively you can use Yarn
$ yarn add localstorage-slim
```
--------------------------------
### Custom Encrypter/Decrypter Implementation Example
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/types.md
Example of using a third-party library like CryptoJS for custom encryption and decryption. Ensure the decrypter returns the parsed value.
```javascript
import CryptoJS from 'crypto-js';
ls.config.encrypter = (data, secret) => {
return CryptoJS.AES.encrypt(JSON.stringify(data), secret).toString();
};
ls.config.decrypter = (encryptedString, secret) => {
const decrypted = CryptoJS.AES.decrypt(encryptedString, secret).toString(CryptoJS.enc.Utf8);
return JSON.parse(decrypted);
};
```
--------------------------------
### Basic Retrieval Example
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/ls-main.md
Demonstrates retrieving a simple string value from storage.
```javascript
// Basic retrieval
const username = ls.get('username');
console.log(username); // 'john_doe'
```
--------------------------------
### Custom Storage Implementation Example
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/internal-implementation.md
An example of a custom storage implementation that adheres to the Storage interface contract. This can be assigned to `ls.config.storage` to use a custom storage mechanism.
```javascript
const customStorage = {
_data: {},
length: 0,
getItem(key) {
return this._data[key] ?? null;
},
setItem(key, value) {
if (!(key in this._data)) this.length++;
this._data[key] = value;
},
removeItem(key) {
if (key in this._data) this.length--;
delete this._data[key];
},
clear() {
this._data = {};
this.length = 0;
},
key(index) {
return Object.keys(this._data)[index] ?? null;
}
};
ls.config.storage = customStorage;
```
--------------------------------
### Example: Explicitly use memoryStore for storage
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/internal-implementation.md
Shows how to configure localstorage-slim to use the in-memory storage implementation, useful for testing or specific environments.
```javascript
// Using memoryStore explicitly
import ls from 'localstorage-slim';
// Opt into in-memory storage
ls.config.storage = memoryStore();
// Now all data is stored in memory
ls.set('temp', 'value');
ls.get('temp'); // 'value'
// On page reload, data is lost
```
--------------------------------
### React Integration Example
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/README.md
Demonstrates how to integrate localstorage-slim with React using `useState` for initial state and `useEffect` for persistence. Ensure the library is imported.
```javascript
import ls from 'localstorage-slim';
import { useState, useEffect } from 'react';
function App() {
const [user, setUser] = useState(() => ls.get('user'));
useEffect(() => {
ls.set('user', user);
}, [user]);
// ... rest of your component
return (
// ... JSX
User: {JSON.stringify(user)}
);
}
```
--------------------------------
### Basic Setup with TTL and Session Storage
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/configuration.md
Configure a default TTL of 1 hour and set the storage to sessionStorage. All subsequent operations will use these settings.
```javascript
import ls from 'localstorage-slim';
// Store with 1-hour default TTL
ls.config.ttl = 3600;
// Use sessionStorage
ls.config.storage = sessionStorage;
// Now all operations use these defaults
ls.set('user', { id: 1, name: 'John' });
ls.get('user'); // returns { id: 1, name: 'John' }
```
--------------------------------
### Remove Key Example
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/ls-main.md
Demonstrates removing a key from storage.
```javascript
// Remove a single key
ls.remove('username');
```
--------------------------------
### Clear All Data Example
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/ls-main.md
Demonstrates the basic usage of `clear()` to empty the entire storage.
```javascript
// Clear all data from localStorage
ls.clear();
```
--------------------------------
### Examples: isObject function return values
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/internal-implementation.md
Illustrates the expected return values of the isObject helper function for various input types.
```javascript
// External examples of what isObject returns
isObject({}) // true
isObject({ a: 1 }) // true
isObject([]) // false (arrays are excluded)
isObject(null) // false (null is excluded)
isObject('string') // false
isObject(123) // false
isObject(new Date()) // true (is technically an object)
```
--------------------------------
### Manage App Preferences with Localstorage-Slim
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/examples-and-patterns.md
Demonstrates how to create a class to manage application preferences using Localstorage-Slim. It includes methods for getting, setting, and resetting preferences, with default values.
```javascript
class PreferenceManager {
private defaults = {
theme: 'light',
language: 'en',
notifications: true,
autoSave: false
};
constructor() {
// Load or initialize preferences
const stored = ls.get('preferences');
if (!stored) {
ls.set('preferences', this.defaults);
}
}
get(key) {
const prefs = ls.get('preferences') || this.defaults;
return prefs[key] ?? this.defaults[key];
}
set(key, value) {
const prefs = ls.get('preferences') || { ...this.defaults };
prefs[key] = value;
ls.set('preferences', prefs);
}
reset() {
ls.set('preferences', this.defaults);
}
}
// Usage
const prefs = new PreferenceManager();
console.log(prefs.get('theme')); // 'light'
prefs.set('theme', 'dark');
console.log(prefs.get('theme')); // 'dark'
```
--------------------------------
### Set and Get Item with LocalStorage-Slim
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/demo/index.html
Demonstrates basic usage of setting a key-value pair and retrieving it using LocalStorage-Slim. This is useful for testing core functionalities.
```javascript
ls.set('key', 'some value');
const res = ls.get('key');
console.log('res =>', res);
```
--------------------------------
### Manual Flush Example
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/ls-main.md
Demonstrates manually calling `flush()` to remove expired items. Items with TTL are set first.
```javascript
// Set items with TTL
ls.set('session1', 'value1', { ttl: 5 });
ls.set('session2', 'value2', { ttl: 10 });
// Manually flush expired items
ls.flush(); // removes only expired items
```
--------------------------------
### Retrieve a Value
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/README.md
Use the `get` method to retrieve a value associated with a key. The library must be imported.
```javascript
const value = ls.get('key');
```
--------------------------------
### Shift Cipher Example
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/internal-implementation.md
Demonstrates encrypting and decrypting the string 'hello' using a secret offset of 75 with the shift cipher. Note that this method provides obfuscation, not true security.
```javascript
const secret = 75;
// Encrypt "hello"
// 'h' (104) + 75 = 179 -> '³'
// 'e' (101) + 75 = 176 -> '°'
// Result: "³°¬¬¯"
// Decrypt "³°¬¬¯"
// 179 - 75 = 104 -> 'h'
// 176 - 75 = 101 -> 'e'
// Result: "hello"
```
--------------------------------
### Basic Data Storage
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/INDEX.md
Demonstrates how to store and retrieve simple string data and complex JavaScript objects using the library's set and get methods.
```javascript
import ls from 'localstorage-slim';
// Store simple data
ls.set('username', 'john_doe');
ls.get('username'); // 'john_doe'
// Store complex objects
ls.set('user', { id: 1, name: 'John', email: 'john@example.com' });
ls.get('user'); // { id: 1, name: 'John', email: 'john@example.com' }
```
--------------------------------
### Dictionary Type Examples
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/types.md
Illustrates the usage of the Dictionary type alias with different value types: strings, numbers, and mixed types using the default.
```typescript
// Dictionary of strings
const config: Dictionary = {
apiUrl: 'https://api.example.com',
version: '2.0'
};
// Dictionary of numbers
const metrics: Dictionary = {
userCount: 1500,
activeSession: 45
};
// Dictionary of mixed types (default)
const store: Dictionary = {
name: 'John',
age: 30,
active: true
};
```
--------------------------------
### Store and retrieve data with localstorage-slim
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/README.md
Demonstrates basic usage of setting and getting data. Supports various data types including objects and arrays. The retrieved data may have values represented as strings.
```javascript
/*** Store in localstorage ***/
const value = {
a: new Date(),
b: null,
c: false,
d: 'superman',
e: 1234
}
ls.set('key1', value); // value can be anything (object, array, string, number, ...)
ls.get('key1'); // { a: "currentdate", b: "null", c: false, d: 'superman', e: 1234 }
```
--------------------------------
### Handle Null Result
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/ls-main.md
Provides an example of checking for a null return value, indicating a missing or expired key.
```javascript
// Handle null result
const maybeValue = ls.get('unknown_key');
if (maybeValue === null) {
console.log('Key does not exist or has expired');
}
```
--------------------------------
### Encrypt Specific Item with Custom Secret
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/README.md
Demonstrates how to encrypt a particular LocalStorage item by providing a custom secret key during the set and get operations.
```javascript
/* After updating the config, use ls as you normally would */
ls.set(...); // internally calls ls.config.encrypter(...);
ls.get(...); // internally calls ls.config.decrypter(...);
/* you can encrypt a particular LS item by providing a different secret as well. */
ls.set("key", "value", { secret: 'xyz'});
ls.get("key", { secret: 'xyz'});
```
--------------------------------
### get(key, config)
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/ls-main.md
Retrieves a value from storage by key. It automatically handles Time-To-Live (TTL) validation and decryption based on provided configuration. Returns null if the key does not exist, if its TTL has expired, or if decryption fails.
```APIDOC
## get(key, config)
### Description
Retrieves a value from storage by key. Automatically handles TTL validation and decryption based on configuration. Returns `null` if the key doesn't exist or if a TTL has expired.
### Method
```typescript
get(key: string, localConfig?: Omit): T | null
```
### Parameters
#### Path Parameters
- **key** (string) - Required - The key to retrieve from storage
- **localConfig** (Omit) - Optional - Configuration options for this specific `get` operation. Overrides global config. Includes: `decrypt`, `decrypter`, `secret`. The `storage` property is not allowed here.
### Response
#### Success Response
- **T** - The stored value (typed as `T` for TypeScript users) if the key exists and is not expired
- **null** - if:
- The key does not exist
- The TTL has expired
- JSON parsing fails and no decryption is applied
- Decryption fails (incorrect secret)
### Request Example
```javascript
// Basic retrieval
const username = ls.get('username');
console.log(username); // 'john_doe'
// Retrieve with type assertion
const profile = ls.get('user_profile');
console.log(profile.name); // 'John Doe'
// Retrieve value stored with TTL
ls.set('temp_key', 'temp_value', { ttl: 5 });
console.log(ls.get('temp_key')); // 'temp_value'
setTimeout(() => {
console.log(ls.get('temp_key')); // null (TTL expired)
}, 6000);
// Retrieve encrypted value
ls.set('secure_data', 'secret', { encrypt: true });
const decrypted = ls.get('secure_data', { decrypt: true });
console.log(decrypted); // 'secret'
// Retrieve when global encryption is enabled
ls.config.encrypt = true;
ls.config.secret = 'my_secret';
const data = ls.get('secure_data'); // automatically decrypts
// Retrieve with custom decryption
const customDecrypted = ls.get('data_key', {
decrypt: true,
secret: 'different_secret'
});
// Handle null result
const maybeValue = ls.get('unknown_key');
if (maybeValue === null) {
console.log('Key does not exist or has expired');
}
```
```
--------------------------------
### Handling Storage Full / Quota Exceeded with set()
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/errors.md
If the browser's storage quota is exceeded, `ls.set()` returns `false`. This example demonstrates filling storage until the quota is met.
```javascript
// Fill storage with large data repeatedly
for (let i = 0; i < 1000; i++) {
const result = ls.set(`key${i}`, new Array(100000).fill('x'));
if (result === false) {
console.warn(`Storage quota exceeded at iteration ${i}`);
break;
}
}
```
--------------------------------
### Handling Encryption Errors with custom encrypter
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/errors.md
If a custom `encrypter` function throws an error (e.g., missing secret), the error propagates. This example shows how to set up a custom encrypter that handles missing secrets gracefully.
```javascript
ls.config.encrypter = (data, secret) => {
if (!secret) {
console.error('Secret missing, returning unencrypted');
return JSON.stringify(data);
}
return CryptoJS.AES.encrypt(data, secret).toString();
};
ls.config.encrypt = true;
// Missing secret:
ls.set('key', 'value'); // throws "Secret is required"
```
--------------------------------
### Handling TTL Expiration with get()
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/errors.md
Items with an expired TTL return `null` and are removed from storage. This example shows setting an item with a TTL and retrieving it after expiration.
```javascript
ls.set('session', 'token123', { ttl: 2 });
console.log(ls.get('session')); // 'token123'
setTimeout(() => {
console.log(ls.get('session')); // null (expired)
console.log(ls.get('session')); // null (removed from storage)
}, 3000);
```
--------------------------------
### Safe Get Pattern for Missing or Expired Data
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/INDEX.md
Demonstrates the safe get pattern for retrieving data, handling cases where the key might not exist or the item has expired. It checks if the returned value is null and logs a message accordingly.
```javascript
const value = ls.get('key');
if (value === null) {
console.log('Key not found or expired');
}
```
--------------------------------
### Build and Watch Package
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/contributing.md
Use this script to build the package and continuously watch for changes during development.
```bash
make watch
```
--------------------------------
### TypeScript Get Function Signature
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/INDEX.md
Signature for the get function, which retrieves a value by key. It supports generic types for the expected return value and optional local configuration. It returns the stored value or null if not found or expired, and handles automatic decryption while removing expired items.
```typescript
get(
key: string,
localConfig?: Omit
): T | null
```
--------------------------------
### Initialize LocalStorage-Slim
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/demo/index.html
This snippet shows how to initialize the LocalStorage-Slim library, including conditional loading for development or production environments.
```javascript
if (dev) {
document.write('
```
--------------------------------
### Angular Service for Local Storage
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/examples-and-patterns.md
An Angular service that wraps localstorage-slim for easy integration into Angular components. It provides methods for getting, setting, removing, and clearing items.
```typescript
// storage.service.ts
import { Injectable } from '@angular/core';
import ls from 'localstorage-slim';
@Injectable({
providedIn: 'root'
})
export class StorageService {
constructor() {
// Configure on initialization
ls.config.ttl = 3600;
}
get(key: string): T | null {
return ls.get(key);
}
set(key: string, value: T, config?: any): void {
ls.set(key, value, config);
}
remove(key: string): void {
ls.remove(key);
}
clear(): void {
ls.clear();
}
}
// Usage in component
export class UserComponent {
constructor(private storage: StorageService) {}
saveUser(user: User): void {
this.storage.set('current_user', user, { ttl: 1800 });
}
loadUser(): User | null {
return this.storage.get('current_user');
}
}
```
--------------------------------
### Using localStorage and sessionStorage with ESM Imports
Source: https://github.com/digitalfortress-tech/localstorage-slim/wiki/FAQ
Demonstrates how to import and configure separate instances of localstorage-slim to manage both localStorage and sessionStorage when using ECMAScript Modules (ESM). Each instance is configured to use a specific storage type.
```js
import ls from 'localstorage-slim';
import ss from 'localstorage-slim';
ss.config.storage = sessionStorage; // configure this instance to use sessionStorage globally
// ls.config.storage = localStorage; (this is not required since the library defaults to using localStorage)
ss.set('item 1', 'value 1'); // stored in sessionStorage
ls.set('item A', 'value A'); // stored in localStorage
```
--------------------------------
### Safe Encryption and Decryption Patterns
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/errors.md
Functions for safely setting and getting encrypted data. These include try-catch blocks to handle potential errors during the encryption or decryption process.
```javascript
const encryptedSet = (key, value, secret) => {
try {
return ls.set(key, value, { encrypt: true, secret });
} catch (error) {
console.error('Encryption error:', error);
return false;
}
};
const encryptedGet = (key, secret) => {
try {
return ls.get(key, { decrypt: true, secret });
} catch (error) {
console.error('Decryption error:', error);
return null;
}
};
```
--------------------------------
### Monitor All Operations with Wrappers
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/internal-implementation.md
This snippet shows how to wrap `ls.set` to log all set operations, including the key, value, and configuration. This technique can be extended to other `ls` methods for debugging.
```javascript
// Wrap methods for logging
const originalSet = ls.set;
ls.set = function(key, value, config) {
console.log('SET', { key, value, config });
return originalSet.call(this, key, value, config);
};
```
--------------------------------
### Get Item from Local Storage
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/README.md
Retrieves data associated with a key from local storage. Returns null if the key does not exist. Supports decryption and TTL expiration checks.
```javascript
const value = ls.get('key');
console.log('Value =>', value); // value retrieved from LS
```
```javascript
// if ttl was set
ls.get('key'); // returns the value if ttl has not expired, else returns null
```
```javascript
// when a particular field is encrypted, and it needs decryption
ls.get('key', { decrypt: true });
```
```javascript
// get decrypted value when global encryption is enabled
ls.config.encrypt = true;
ls.get('key'); // returns decrypted value
```
--------------------------------
### Import localstorage-slim
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/ls-main.md
Import the default export from the localstorage-slim library.
```typescript
import ls from 'localstorage-slim';
```
--------------------------------
### Global Configuration Options
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/INDEX.md
View and modify global configuration settings for the library, such as default TTL, encryption status, encryption key, and storage backend.
```javascript
import ls from 'localstorage-slim';
// View/modify configuration
ls.config.ttl = 300; // Default expiration (seconds)
ls.config.encrypt = true; // Enable encryption
ls.config.secret = 'password'; // Encryption key
ls.config.storage = localStorage; // Storage backend
```
--------------------------------
### Store and Retrieve a String
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/examples-and-patterns.md
Demonstrates the basic usage of `ls.set()` and `ls.get()` to store and retrieve a simple string value.
```javascript
import ls from 'localstorage-slim';
// Store
ls.set('username', 'alice');
// Retrieve
const username = ls.get('username');
console.log(username); // 'alice'
```
--------------------------------
### Type-Safe Usage with Generics
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/internal-implementation.md
Demonstrates how to use the generic `get` method in TypeScript to specify the expected type of the retrieved data, enabling compile-time type checking and preventing runtime errors.
```typescript
// With TypeScript
const user = ls.get<{ id: number; name: string }>('user');
user.id; // OK, type is number
user.age; // Error, property doesn't exist
const num = ls.get('count');
num + 1; // OK, type is number
num.toUpperCase(); // Error, numbers don't have this method
```
--------------------------------
### Override Secret Per-Call
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/configuration.md
Set or get data using a specific secret key for a single operation, overriding the globally configured secret. This is useful for managing different security levels for different data.
```javascript
// Per-call secret override
ls.set('data1', 'value1', { secret: 'secret1' });
ls.set('data2', 'value2', { secret: 'secret2' });
ls.get('data1', { secret: 'secret1' }); // correct secret
ls.get('data2', { secret: 'secret2' }); // different secret
// Wrong secret returns encrypted value
ls.get('data1', { secret: 'wrong' }); // returns encrypted, not decrypted
```
--------------------------------
### Mixed Configuration for TTL and Encryption
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/configuration.md
Demonstrates setting specific TTLs and encryption options for individual items, overriding global configurations. This allows for granular control over data persistence and security.
```javascript
import ls from 'localstorage-slim';
// Some items with TTL, some without
ls.set('session_token', 'abc123', { ttl: 1800 }); // 30 minutes
ls.set('user_preference', 'dark_mode', { ttl: null }); // permanent
// Some items encrypted, some not
ls.config.encrypt = false;
ls.set('public_data', 'everyone sees'); // not encrypted
ls.set('private_data', 'secret', { encrypt: true }); // encrypted
// Different secrets for different data
ls.set('data1', 'value1', { secret: 'key1' });
ls.set('data2', 'value2', { secret: 'key2' });
```
--------------------------------
### Core API Methods
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/INDEX.md
Reference for the core methods available in the localstorage-slim library for interacting with storage.
```APIDOC
## set(key, value, localConfig)
### Description
Stores a key-value pair in local storage. Supports optional TTL and encryption. Overwrites existing values if the key already exists.
### Method
`set(key: string, value: T, localConfig?: Omit): void | boolean`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **key** (string) - Required - The key under which to store the value.
- **value** (T) - Required - The value to store. Can be of any JSON-serializable type.
- **localConfig** (Omit) - Optional - Configuration specific to this operation, such as `ttl`, `encrypt`, `secret`, etc.
### Response
- Returns `undefined` on successful storage.
- Returns `false` if a serialization error occurs.
### Examples
```javascript
// Basic set
ls.set('username', 'john_doe');
// Set with TTL and encryption
ls.set('sensitive_data', { token: 'abc123xyz' }, { ttl: 300, encrypt: true, secret: 'mysecret' });
```
## get(key, localConfig)
### Description
Retrieves a value from local storage by its key. Handles automatic decryption and removes expired items.
### Method
`get(key: string, localConfig?: Omit): T | null`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **key** (string) - Required - The key of the item to retrieve.
- **localConfig** (Omit) - Optional - Configuration to apply for decryption if needed.
### Response
- Returns the stored value of type `T` if found and not expired.
- Returns `null` if the key is not found, has expired, or an error occurs during decryption.
### Examples
```javascript
// Get a value
const username = ls.get('username');
// Get encrypted data
const data = ls.get<{ token: string }>('sensitive_data', { decrypt: true });
// Handle not found or expired
if (data === null) {
console.log('Data not found or expired.');
}
```
## remove(key)
### Description
Deletes a specific item from local storage by its key.
### Method
`remove(key: string): void`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **key** (string) - Required - The key of the item to remove.
### Response
- Returns `undefined`. The operation is silent if the key does not exist.
### Examples
```javascript
ls.remove('username');
```
## clear()
### Description
Removes all items from local storage. This operation cannot be undone.
### Method
`clear(): void`
### Parameters
None
### Response
- Returns `undefined`.
### Examples
```javascript
ls.clear();
```
## flush(force)
### Description
Manages the removal of expired items from local storage.
### Method
`flush(force?: boolean): void`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **force** (boolean) - Optional - If `true`, removes all items with a TTL. If `false` or omitted, only removes expired items.
### Response
- Returns `undefined`.
### Examples
```javascript
// Remove only expired items
ls.flush();
// Remove all items with a TTL
ls.flush(true);
```
```
--------------------------------
### Use Local Storage
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/configuration.md
Configure the library to use localStorage, which is the default behavior. Data persists even after the browser is closed.
```javascript
ls.config.storage = localStorage;
```
--------------------------------
### Safe Get Pattern for Storage Retrieval
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/errors.md
A utility function to safely retrieve a value from storage, returning a specified default value if the key is not found or an error occurs. This prevents unexpected nulls or undefined values.
```javascript
const safeGet = (key, defaultValue = null) => {
const value = ls.get(key);
return value !== null ? value : defaultValue;
};
// Usage
const user = safeGet('user', { id: null, name: 'Guest' });
```
--------------------------------
### First Call Initialization Trigger
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/internal-implementation.md
The initialization function `init()` is automatically called the first time any public method of the library is invoked, ensuring the storage backend is ready before operations commence.
```javascript
ls.set('key', 'value'); // Triggers init()
```
--------------------------------
### Storage Interface Contract
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/internal-implementation.md
Defines the contract that all storage implementations must adhere to, including methods for getting, setting, removing items, clearing storage, and accessing item count and keys. Values are always stored as strings.
```typescript
interface Storage {
readonly length: number;
clear(): void;
getItem(key: string): string | null;
key(index: number): string | null;
removeItem(key: string): void;
setItem(key: string, value: string): void;
}
```
--------------------------------
### Shared Storage Instance
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/internal-implementation.md
Illustrates that multiple imports of the 'localstorage-slim' library within the same environment share the same underlying storage instance due to the module-level state management.
```javascript
// All of these share the same storage instance
import ls1 from 'localstorage-slim';
import ls2 from 'localstorage-slim';
ls1.set('key', 'value');
console.log(ls2.get('key')); // 'value' (same storage)
```
--------------------------------
### Web Storage API Interface
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/types.md
Defines the standard Web Storage API interface that custom storage implementations must adhere to. This includes methods for getting, setting, removing items, clearing storage, and accessing item counts and keys by index.
```typescript
interface Storage {
length: number;
clear(): void;
getItem(key: string): string | null;
key(index: number): string | null;
removeItem(key: string): void;
setItem(key: string, value: string): void;
}
```
--------------------------------
### Use Session Storage
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/ls-main.md
Configure the library to use sessionStorage instead of the default localStorage.
```javascript
ls.config.storage = sessionStorage;
```
--------------------------------
### Store a Value
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/README.md
Use the `set` method to store a key-value pair. Ensure the library is imported first.
```javascript
import ls from 'localstorage-slim';
ls.set('key', 'value');
```
--------------------------------
### Use Custom Storage Implementation
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/README.md
Configure LocalStorage-Slim to use a custom storage object, which must implement the standard Storage interface.
```javascript
/* OR a custom store/storage via an IIFE */
ls.config.storage = (() => {
const store = {
// your storage's implementation...
};
return store;
})();
```
--------------------------------
### Import localstorage-slim as a module
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/README.md
Import the library into your JavaScript project using ES6 modules or CommonJS.
```javascript
// using ES6 modules
import ls from 'localstorage-slim';
// using CommonJS modules
var ls = require('localstorage-slim');
```
--------------------------------
### Enable Encryption
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/README.md
To enable encryption, set `ls.config.encrypt` to true and provide a secret. Then, use the `set` method to store encrypted data.
```javascript
ls.config.encrypt = true;
ls.config.secret = 'password';
ls.set('key', 'value');
```
--------------------------------
### Lazy-Loaded Storage Wrapper
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/examples-and-patterns.md
Implement a wrapper that defers loading data from local storage until it's actually accessed, improving initial load times. Subsequent accesses retrieve data from an in-memory cache.
```javascript
class LazyStorage {
constructor() {
this.cache = new Map();
this.loaded = new Map();
}
get(key) {
if (!this.loaded.has(key)) {
const value = ls.get(key);
this.cache.set(key, value);
this.loaded.set(key, true);
}
return this.cache.get(key);
}
set(key, value) {
this.cache.set(key, value);
this.loaded.set(key, true);
return ls.set(key, value);
}
flush() {
this.cache.clear();
this.loaded.clear();
}
}
// Usage
const storage = new LazyStorage();
storage.get('user'); // Loads from LS
storage.get('user'); // Returns cached value (no LS access)
storage.set('user', newValue); // Updates cache and LS
```
--------------------------------
### Retrieve Value with TTL
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/ls-main.md
Illustrates retrieving a value set with a Time-To-Live (TTL) and demonstrates its expiration.
```javascript
// Retrieve value stored with TTL
ls.set('temp_key', 'temp_value', { ttl: 5 });
console.log(ls.get('temp_key')); // 'temp_value'
setTimeout(() => {
console.log(ls.get('temp_key')); // null (TTL expired)
}, 6000);
```
--------------------------------
### Setting Default and Specific TTL
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/INDEX.md
Illustrates how to set a default expiration time for all stored items and how to specify a unique TTL for individual items.
```javascript
// Set 5-minute default TTL
ls.config.ttl = 300;
// Store session token (expires in 5 minutes)
ls.set('session_token', 'abc123xyz');
// Or set specific TTL per item
ls.set('temp_data', { key: 'value' }, { ttl: 60 }); // 1 minute
// Retrieve (returns null if expired)
console.log(ls.get('session_token')); // token within 5 min, null after
```
--------------------------------
### Use Custom In-Memory Storage
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/examples-and-patterns.md
Implement and configure a custom in-memory object as the storage backend for localstorage-slim. This is useful for temporary data that should not persist across page reloads.
```javascript
import ls from 'localstorage-slim';
// Use custom in-memory store
ls.config.storage = {
_store: {},
length: 0,
getItem(key) {
return this._store[key] ?? null;
},
setItem(key, value) {
if (!(key in this._store)) this.length++;
this._store[key] = value;
},
removeItem(key) {
if (key in this._store) this.length--;
delete this._store[key];
},
clear() {
this._store = {};
this.length = 0;
},
key(index) {
return Object.keys(this._store)[index] ?? null;
}
};
// Data is now in memory only - lost on page reload
ls.set('temp', 'value');
```
--------------------------------
### Integrate IndexedDB as Storage Backend
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/examples-and-patterns.md
Wrap IndexedDB to use it as a custom storage backend for localstorage-slim. This allows for larger storage capacity and more robust data management.
```javascript
import ls from 'localstorage-slim';
// Wrapper for IndexedDB as custom storage
const idbStorage = {
db: null,
async init() {
return new Promise((resolve) => {
const req = indexedDB.open('mydb', 1);
req.onupgradeneeded = (e) => {
e.target.result.createObjectStore('storage');
};
req.onsuccess = (e) => {
this.db = e.target.result;
resolve();
};
});
},
getItem(key) {
if (!this.db) return null;
const tx = this.db.transaction('storage', 'readonly');
const store = tx.objectStore('storage');
const req = store.get(key);
return new Promise((resolve) => {
req.onsuccess = () => resolve(req.result ?? null);
});
},
setItem(key, value) {
const tx = this.db.transaction('storage', 'readwrite');
const store = tx.objectStore('storage');
store.put(value, key);
},
removeItem(key) {
const tx = this.db.transaction('storage', 'readwrite');
const store = tx.objectStore('storage');
store.delete(key);
},
clear() {
const tx = this.db.transaction('storage', 'readwrite');
const store = tx.objectStore('storage');
store.clear();
},
key(index) {
const tx = this.db.transaction('storage', 'readonly');
const store = tx.objectStore('storage');
const req = store.getAllKeys();
return new Promise((resolve) => {
req.onsuccess = () => resolve(req.result[index] ?? null);
});
}
};
// Usage
await idbStorage.init();
ls.config.storage = idbStorage;
ls.set('data', 'value'); // Uses IndexedDB
```
--------------------------------
### ls.get(key, config)
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/README.md
Retrieves the data associated with a key from LocalStorage. It accepts a key and an optional configuration object for decryption.
```APIDOC
## `ls.get(key, config = {})`
### Description
Retrieves the Data associated with the key stored in the LocalStorage. It accepts 2 arguments: `key` and an optional `config` object.
### Parameters
#### Path Parameters
- **key** (string) - Required - The key with which the value is associated
- **config** (Config) - Optional - Accepts properties like `decrypt`. Defaults to an empty object.
### Returns
If the passed key does not exist, it returns `null`. Otherwise, it returns the retrieved value.
### Request Example
```javascript
const value = ls.get('key');
console.log('Value =>', value); // value retrieved from LS
// if ttl was set
ls.get('key'); // returns the value if ttl has not expired, else returns null
// when a particular field is encrypted, and it needs decryption
ls.get('key', { decrypt: true });
// get decrypted value when global encryption is enabled
ls.config.encrypt = true;
ls.get('key'); // returns decrypted value
```
```
--------------------------------
### Cleanup with Force Flush
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/ls-main.md
Illustrates using `flush(true)` as a cleanup mechanism for temporary data marked with TTL.
```javascript
// Flush as cleanup after a long operation
ls.set('temp1', 'data1', { ttl: 3600 });
ls.set('temp2', 'data2', { ttl: 3600 });
// ... later
ls.flush(true); // clear all temp data regardless of TTL
```
--------------------------------
### Configure Custom AES Encryption with CryptoJS
Source: https://github.com/digitalfortress-tech/localstorage-slim/blob/master/_autodocs/api-reference/examples-and-patterns.md
Set up CryptoJS for AES encryption and decryption by providing custom functions to localstorage-slim's configuration. This enables global encryption for all stored data.
```javascript
import CryptoJS from 'crypto-js';
import ls from 'localstorage-slim';
// Configure AES encryption
ls.config.secret = 'super-secret-password-123';
ls.config.encrypter = (data, secret) => {
return CryptoJS.AES.encrypt(data, secret).toString();
};
ls.config.decrypter = (encryptedString, secret) => {
const decrypted = CryptoJS.AES.decrypt(encryptedString, secret)
.toString(CryptoJS.enc.Utf8);
return JSON.parse(decrypted);
};
// Enable global encryption
ls.config.encrypt = true;
// Now all data is AES-encrypted
ls.set('database_password', 'secret123');
ls.set('api_credentials', { key: 'abc', secret: 'xyz' });
// Retrieve automatically decrypted
console.log(ls.get('database_password')); // 'secret123'
console.log(ls.get('api_credentials')); // { key: 'abc', secret: 'xyz' }
```