safe-storage-ts
v1.0.1
Published
Zero-dependency, type-safe browser storage wrapper (localStorage & sessionStorage) with TTL expiry, SSR memory fallback, namespace prefixes, and change listeners.
Maintainers
Readme
🛡️ safe-storage-ts
Zero-dependency, type-safe browser storage wrapper (
localStorage&sessionStorage) with TTL expiry, SSR memory fallback, namespace prefixes, and change listeners.
✨ Features
- 🔒 Full Type-Safety — Seamless generics
storage.get<User>('user')for objects, arrays, numbers, and booleans. - ⏳ TTL & Automatic Expiry — Set expiration in seconds or with a
Dateobject; expired entries are purged automatically. - 🌐 SSR & Incognito Safe — Gracefully falls back to an in-memory storage backend if
window,localStorage, or quota is unavailable. - 🏷️ Namespaces & Prefixing — Isolate storage keys easily across different features, apps, or multi-tenant sessions.
- 📡 Reactive Listeners — Subscribe to key changes across tabs or locally with
.subscribe(key, (newVal, oldVal) => ...). - ⚡ Zero Dependencies — Ultra-lightweight (~2 KB minified), purely native TypeScript.
- 📦 Dual ESM & CommonJS — Compatible with Next.js, Nuxt, Remix, Vite, React, Node.js, and vanilla apps.
📥 Installation
npm install safe-storage-tsor with Yarn / pnpm:
pnpm add safe-storage-ts
# or
yarn add safe-storage-ts🚀 Quick Start
1. Simple Type-Safe Storage
import { safeLocalStorage } from 'safe-storage-ts';
interface UserProfile {
id: string;
name: string;
email: string;
}
// Store an object directly (no manual JSON.stringify needed)
safeLocalStorage.set('profile', {
id: 'usr_123',
name: 'Alex Doe',
email: '[email protected]',
});
// Retrieve with complete TypeScript type inference
const user = safeLocalStorage.get<UserProfile>('profile');
console.log(user?.name); // Alex Doe2. Time-To-Live (TTL) & Expiry
Auto-expire tokens, cache responses, or sessions after a set duration:
import { safeLocalStorage } from 'safe-storage-ts';
// Expire after 3600 seconds (1 hour)
safeLocalStorage.set('auth_token', 'xyz-secret-token', { ttl: 3600 });
// Or shorthand number:
safeLocalStorage.set('temp_banner_dismissed', true, 86400); // 24 hours
// Check remaining seconds before expiration:
const remainingSecs = safeLocalStorage.getRemainingTTL('auth_token');
console.log(`Token expires in ${remainingSecs} seconds`);
// Once expired, get() automatically purges the item and returns null or fallback:
const token = safeLocalStorage.get('auth_token', null);3. Isolated Namespaces & Prefixing
Prevent key collisions by creating dedicated storage scopes:
import { createStorage } from 'safe-storage-ts';
const authStorage = createStorage({
type: 'localStorage',
prefix: 'app_auth_',
});
const cartStorage = createStorage({
type: 'sessionStorage',
prefix: 'app_cart_',
});
authStorage.set('token', 'secret123'); // Stored as "app_auth_token"
cartStorage.set('items', ['apple', 'orange']); // Stored as "app_cart_items" in sessionStorage
// Clear only cart items without affecting auth:
cartStorage.clear();4. Reactive Change Listeners
Listen to updates on specific keys:
import { safeLocalStorage } from 'safe-storage-ts';
const unsubscribe = safeLocalStorage.subscribe('theme', (newTheme, oldTheme) => {
console.log(`Theme changed from ${oldTheme} to ${newTheme}`);
document.documentElement.setAttribute('data-theme', newTheme);
});
// Update value
safeLocalStorage.set('theme', 'dark');
// Stop listening when component unmounts
unsubscribe();⚙️ API Reference
createStorage(options)
| Option | Type | Default | Description |
|---|---|---|---|
| type | 'localStorage' \| 'sessionStorage' \| 'memory' | 'localStorage' | Storage backend mechanism. |
| prefix | string | '' | Prefix prepended to all stored keys. |
| serializer | (val: unknown) => string | JSON.stringify | Custom string serializer. |
| deserializer | (str: string) => unknown | JSON.parse | Custom parser. |
| onError | (err, action) => void | undefined | Error hook for storage exceptions (quota, etc.). |
SafeStorage Methods
| Method | Return Type | Description |
|---|---|---|
| set<T>(key, value, options?) | boolean | Stores a value with optional { ttl } or { expiresAt }. |
| get<T>(key, fallback?) | T \| null | Retrieves value. Purges and returns fallback if expired. |
| getRemainingTTL(key) | number \| null | Returns remaining seconds until expiration, or null. |
| has(key) | boolean | Checks if key exists and is unexpired. |
| remove(key) | boolean | Removes specific key. |
| clear() | boolean | Clears all keys belonging to this instance's prefix. |
| keys() | string[] | Lists all keys (prefix stripped). |
| size() | number | Count of keys stored. |
| subscribe<T>(key, callback) | () => void | Listens to key updates. Returns unsubscribe function. |
| isUsingMemory() | boolean | True if fallback memory storage is active. |
🛠 Development & Testing
# Install dependencies
npm install
# Run unit tests
npm test
# Build dual ESM/CJS bundles + .d.ts types
npm run build💖 Support the Project
If you find this package useful, consider sponsoring its ongoing development and maintenance: 👉 Sponsor @Piratha97 on GitHub Sponsors
📄 License
MIT © 2026 Pirapaakaran Pirathapan
