Client-Side Storage Options
Browsers provide several distinct client-side storage mechanisms tailored for different persistence requirements and data scales.
Storage Mechanism Matrix
- localStorage: 5-10MB, persistent across sessions, synchronous key-value strings.
- sessionStorage: 5MB, destroyed when tab/window closes, synchronous key-value strings.
- Cookies: 4KB, sent with every HTTP request header. Use
HttpOnlyandSameSiteflags to mitigate XSS/CSRF! - IndexedDB: 100MB+, asynchronous NoSQL object database supporting indexes and transactions.
XSS Security Risk Warning
Never store sensitive JWT tokens or secrets in localStorage! Any XSS vulnerability allows malicious scripts to read localStorage directly via window.localStorage.
The Challenge: TTL Storage Wrapper
Implement a SafeStorage object wrapping localStorage with automated Time-To-Live (TTL) expiration:
setItem(key, value, ttlMs): Stores JSON payload containingvalueand anexpiryTimestamp.getItem(key): Reads payload. IfDate.now() > expiryTimestamp, removes key and returnsnull. Otherwise returnsvalue.