@therafiali/localstorage-utils
A comprehensive, general-purpose localStorage utility library for any JavaScript/TypeScript project
629
| Install | |
|---|---|
npm install @therafiali/localstorage-utils |
|
| Latest Version: | 1.0.2 |
| License: | MIT |
| Last Updated: | Sep 24, 2025 |
| Links: | GitHub · npm |
Maintainer: therafiali
localStorage-utils
A comprehensive, general-purpose localStorage utility library for any JavaScript/TypeScript project.
Features
- ✅ SSR Safe - Works with Next.js, Remix, and other SSR frameworks
- ✅ TypeScript Support - Full type safety and IntelliSense
- ✅ Framework Agnostic - Works with React, Vue, Angular, or vanilla JS
- ✅ Error Handling - Graceful fallbacks and error logging
- ✅ Batch Operations - Perform multiple operations efficiently
- ✅ Expiration Support - Store data with automatic expiration
- ✅ Pattern Matching - Find and manage keys by pattern
- ✅ Size Monitoring - Check localStorage usage
- ✅ Cross-tab Sync - Automatic synchronization across browser tabs
- ✅ Data Encryption - Optional encryption for sensitive data
- ✅ Data Migration - Versioned data migration support
- ✅ React Hooks - Built-in React hooks for reactive state
- ✅ Manager Pattern - Pre-configured localStorage managers
Installation
npm install @therafiali/localstorage-utils
Quick Start
Here are some simple examples to get you started immediately:
Basic Save & Get
import {
saveToLocalStorage,
getFromLocalStorage,
} from "@therafiali/localstorage-utils";
// Save user data
saveToLocalStorage("user", { name: "John", email: "john@example.com" });
// Get user data with fallback
const user = getFromLocalStorage("user", { name: "", email: "" });
console.log(user.name); // "John"
Simple Settings
import {
saveToLocalStorage,
getFromLocalStorage,
} from "@therafiali/localstorage-utils";
// Save theme preference
saveToLocalStorage("theme", "dark");
// Get theme preference
const theme = getFromLocalStorage("theme", "light");
document.body.className = theme;
Shopping Cart
import {
saveToLocalStorage,
getFromLocalStorage,
} from "@therafiali/localstorage-utils";
// Add item to cart
const cart = getFromLocalStorage("cart", []);
cart.push({ id: 1, name: "Laptop", price: 999 });
saveToLocalStorage("cart", cart);
// Get cart items
const items = getFromLocalStorage("cart", []);
console.log(`Cart has ${items.length} items`);
Clear Data
import {
removeFromLocalStorage,
clearAllLocalStorage,
} from "@therafiali/localstorage-utils";
// Remove specific item
removeFromLocalStorage("user");
// Clear everything
clearAllLocalStorage();
Simple Mapping Lookup
import {
lookupFromMapping,
saveToLocalStorage,
} from "@therafiali/localstorage-utils";
// First, save some mapping data
const teamMappings = [{ team1: "Team Alpha" }, { team2: "Team Beta" }];
saveToLocalStorage("team_mappings", teamMappings);
// Lookup team name
const teamName = lookupFromMapping("team1", "team_mappings", "Unknown Team");
console.log(teamName); // "Team Alpha"
Usage
Basic Operations
import {
getFromLocalStorage,
saveToLocalStorage,
removeFromLocalStorage,
} from "@therafiali/localstorage-utils";
// Save data
saveToLocalStorage("user", { name: "John", age: 30 });
// Get data with fallback
const user = getFromLocalStorage("user", { name: "", age: 0 });
// Remove data
removeFromLocalStorage("user");
// Save with encryption
saveToLocalStorage("sensitive", { token: "secret" }, { encrypt: true });
// Get with custom error handler
const data = getFromLocalStorage("data", null, {
onError: (error, operation) => {
console.log(`Error in ${operation}:`, error.message);
},
});
Batch Operations
import { createBatch } from "@therafiali/localstorage-utils";
const batch = createBatch()
.set("user", { name: "John" })
.set("settings", { theme: "dark" })
.remove("oldData");
batch.execute(); // Apply all operations at once
Expiration Support
import { LocalStorageWithExpiry } from "@therafiali/localstorage-utils";
// Set data that expires in 30 minutes
LocalStorageWithExpiry.set("token", "abc123", 30);
// Get data (automatically removes if expired)
const token = LocalStorageWithExpiry.get("token", "");
// Clean up expired items
LocalStorageWithExpiry.removeExpired();
Pattern Matching
import {
getLocalStorageKeysByPattern,
clearLocalStorageByPattern,
} from "@therafiali/localstorage-utils";
// Find all keys containing 'user'
const userKeys = getLocalStorageKeysByPattern("user");
// Remove all keys containing 'temp'
const removed = clearLocalStorageByPattern("temp");
Mapping Lookup
import { lookupFromMapping } from "@therafiali/localstorage-utils";
// Lookup team ID from mapping
const teamId = lookupFromMapping(
"team123",
"specific_agent_team_ids",
"team123" // fallback value
);
// Lookup user ID from mapping
const userId = lookupFromMapping("user456", "user_mappings", "user456");
// Lookup with encryption
const configValue = lookupFromMapping(
"config_key",
"encrypted_mappings",
"default_value",
{ encrypt: true }
);
Utility Functions
import {
isLocalStorageAvailable,
getLocalStorageSize,
getAllLocalStorageKeys,
} from "@therafiali/localstorage-utils";
// Check if localStorage is available
if (isLocalStorageAvailable()) {
// Safe to use localStorage
}
// Get storage size
const size = getLocalStorageSize(); // bytes
// Get all keys
const keys = getAllLocalStorageKeys();
Framework Examples
React
import {
useLocalStorage,
useLocalStorageWithExpiry,
} from "@therafiali/localstorage-utils";
function MyComponent() {
// Basic localStorage hook
const [user, setUser, removeUser] = useLocalStorage("user", null);
// localStorage with expiration (30 minutes)
const [token, setToken] = useLocalStorageWithExpiry("token", "", 30);
// With custom options
const [settings, setSettings] = useLocalStorage(
"settings",
{},
{
encrypt: true,
sync: true,
}
);
return (
<div>
<div>User: {user?.name}</div>
<button onClick={() => setUser({ name: "John" })}>Set User</button>
<button onClick={removeUser}>Remove User</button>
</div>
);
}
Vue
import {
getFromLocalStorage,
saveToLocalStorage,
} from "@therafiali/localstorage-utils";
export default {
data() {
return {
user: getFromLocalStorage("user", null),
};
},
methods: {
updateUser(newUser) {
this.user = newUser;
saveToLocalStorage("user", newUser);
},
},
};
Cross-tab Synchronization
import { addStorageListener } from "@therafiali/localstorage-utils";
// Listen for changes across tabs
const removeListener = addStorageListener((event) => {
console.log(`Key ${event.key} changed:`, {
oldValue: event.oldValue,
newValue: event.newValue,
timestamp: event.timestamp,
});
});
// Remove listener when done
removeListener();
Data Migration
import { LocalStorageMigration } from "@therafiali/localstorage-utils";
// Set current version
LocalStorageMigration.setVersion(2);
// Add migration for version 2
LocalStorageMigration.addMigration({
version: 2,
migrate: (data) => {
// Transform data from version 1 to version 2
return {
...data,
newField: "defaultValue",
version: 2,
};
},
});
// Migrate data automatically
const migratedData = LocalStorageMigration.migrateData("user", {});
Manager Pattern
import { createLocalStorageManager } from "@therafiali/localstorage-utils";
// Create a pre-configured manager
const storage = createLocalStorageManager({
encrypt: true,
onError: (error, operation) => {
console.error(`Storage ${operation} failed:`, error);
},
});
// Use the manager
storage.set("user", { name: "John" });
const user = storage.get("user", {});
storage.remove("user");
Vanilla JavaScript
<script type="module">
import {
saveToLocalStorage,
getFromLocalStorage,
} from "@therafiali/localstorage-utils";
// Save user preference
saveToLocalStorage("theme", "dark");
// Get user preference
const theme = getFromLocalStorage("theme", "light");
document.body.className = theme;
</script>
API Reference
Core Functions
getFromLocalStorage<T>(key: string, fallback: T, options?: LocalStorageOptions): TsaveToLocalStorage<T>(key: string, data: T, options?: LocalStorageOptions): booleanremoveFromLocalStorage(key: string): booleanclearAllLocalStorage(): boolean
Pattern Functions
getLocalStorageKeysByPattern(pattern: string): string[]clearLocalStorageByPattern(pattern: string): number
Mapping Functions
lookupFromMapping<T>(key: string, mappingKey: string, fallbackValue: T, options?: LocalStorageOptions): T
Utility Functions
isLocalStorageAvailable(): booleangetLocalStorageSize(): numbergetAllLocalStorageKeys(): string[]getAllLocalStorageData(): Record<string, any>
Batch Operations
createBatch(): LocalStorageBatchLocalStorageBatch.set<T>(key: string, value: T): thisLocalStorageBatch.remove(key: string): thisLocalStorageBatch.execute(): boolean
Expiration Support
LocalStorageWithExpiry.set<T>(key: string, value: T, expiryInMinutes: number): booleanLocalStorageWithExpiry.get<T>(key: string, fallback: T): TLocalStorageWithExpiry.removeExpired(): number
Cross-tab Synchronization
addStorageListener(listener: StorageListener): () => voidremoveAllStorageListeners(): void
Data Migration
LocalStorageMigration.addMigration(migration: Migration): voidLocalStorageMigration.migrateData<T>(key: string, fallback: T): TLocalStorageMigration.setVersion(version: number): void
React Hooks
useLocalStorage<T>(key: string, initialValue: T, options?: LocalStorageOptions): [T, (value: T | ((prev: T) => T)) => void, () => void]useLocalStorageWithExpiry<T>(key: string, initialValue: T, expiryInMinutes: number, options?: LocalStorageOptions): [T, (value: T) => void, () => void]
Manager Pattern
createLocalStorageManager(options?: LocalStorageOptions): LocalStorageManager
License
MIT
Related Packages
@tomassjosten/local-storage-cache
Leverage local storage to improve perfomance by caching data and expire cache
166
1
@vaultdrop/sdk
VaultDrop SDK for browsers — Web Crypto AES-GCM and API client for React, Vue, A...
1,273
@abarchibody/storage
Storage is plugin that help to store data in the local storage, or retrieve data
935
Version History
| Version | Released | License |
|---|---|---|
| 1.0.2 | MIT | |
| 1.0.1 | MIT | |
| 1.0.0 | MIT |