Simple browser cache with TTL using localStorage or memory fallback.
npm install browser-cache-ttllocalStorage when available
Map (Incognito / restricted environments)
bash
npm install browser-cache-ttl
`
or
`bash
yarn add browser-cache-ttl
`
`ts
import { CacheManager } from 'browser-cache-ttl';
const cache = new CacheManager();
cache.set('token', 'abc123', 60); // 1 minute
const token = cache.get('token');
// -> 'abc123' or null if expired
`
TTL (Time To Live)
Each entry must define a TTL in seconds.
`ts
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:
`ts
const cache = new CacheManager({
cleanupIntervalMs: 30 // every 30 seconds
});
`
You can also stop cleanup if needed:
`ts
cache.destroy();
`
Type Safety
The cache is fully typed.
`ts
cache.set('settings', { theme: 'dark' }, 10);
const settings = cache.get<{ theme: string }>('settings');
`
API
`bash
set(key: string, value: T, ttlMs: number): void
`
Stores a value with TTL.
`bash
get(key: string): T | null
`
Returns the value if it exists and is not expired.
`bash
has(key: string): boolean
`
Checks if a key exists and is not expired.
`bash
delete(key: string): void
`
Removes a key from cache.
`bash
stopCleanupTask(): void
`
Stops automatic TTL cleanup.
Storage Strategy
| Environment | Storage Used |
| ---------------------- | --------------- |
| Normal browser mode | localStorage |
| Incognito / restricted | In-memory Map |
Example: Cache with Fallback
`ts
const cache = new CacheManager();
cache.set('session', 'active', 5);
setTimeout(() => {
console.log(cache.get('session')); // null after expiration
}, 6000);
``