browser-cache-ttl
v1.0.8
Published
Simple browser cache with TTL using localStorage or memory fallback.
Maintainers
Readme
Browser Cache with TTL
A tiny, dependency-free browser cache with TTL support, automatic expiration, and smart fallback.
- Uses
localStoragewhen available - Falls back to in-memory
Map(Incognito / restricted environments) - Written in TypeScript
- Automatic cleanup by TTL (not lazy-only)
- Simple and predictable API
Installation
npm install browser-cache-ttlor
yarn add browser-cache-ttlimport { CacheManager } from 'browser-cache-ttl';
const cache = new CacheManager();
cache.set('token', 'abc123', 60); // 1 minute
const token = cache.get<string>('token');
// -> 'abc123' or null if expiredTTL (Time To Live)
Each entry must define a TTL in seconds.
cache.set('user', { id: 1, name: 'Alice' }, 30);After expiration, the value is automatically removed.
Automatic Cleanup
The cache runs a background cleanup task that removes expired entries.
Default cleanup interval: 60 seconds
You can customize it:
const cache = new CacheManager({
cleanupIntervalMs: 30 // every 30 seconds
});You can also stop cleanup if needed:
cache.destroy();Type Safety
The cache is fully typed.
cache.set('settings', { theme: 'dark' }, 10);
const settings = cache.get<{ theme: string }>('settings');API
set<T>(key: string, value: T, ttlMs: number): voidStores a value with TTL.
get<T>(key: string): T | nullReturns the value if it exists and is not expired.
has(key: string): booleanChecks if a key exists and is not expired.
delete(key: string): voidRemoves a key from cache.
stopCleanupTask(): voidStops automatic TTL cleanup.
Storage Strategy
| Environment | Storage Used |
| ---------------------- | --------------- |
| Normal browser mode | localStorage |
| Incognito / restricted | In-memory Map |
Example: Cache with Fallback
const cache = new CacheManager();
cache.set('session', 'active', 5);
setTimeout(() => {
console.log(cache.get('session')); // null after expiration
}, 6000);Browser Support
- Chrome
- Firefox
- Safari
- Edge Works in Incognito / Private mode.
License
MIT
Free to use. Free to modify. Free for everyone.
