Client-Side Storage
localStorage, sessionStorage, IndexedDB, cookies and the Cache API: what each is for, limits and security implications.
Intermediate · about 3 hours · difficulty 2/5
Learn first: Asynchronous JavaScript: Callbacks, Promises and async/await, Authentication, Token Storage and CSRF
Browsers offer several places to keep data on the user's device. Choosing the right one depends on size, structure, lifetime and who needs to read it.
The options
- localStorage: synchronous key-value strings that persist across sessions, per origin, roughly 5 MB. Good for small preferences like theme or a dismissed banner. Store objects with
JSON.stringifyand parse defensively. - sessionStorage: same API, but scoped to one tab and cleared when it closes. Good for in-progress wizard state.
- IndexedDB: an asynchronous, transactional database for large structured data, blobs and offline-first apps. The raw API is verbose; use a wrapper such as
idbor Dexie. - Cookies: small, sent with every request to the server. Use them for sessions (HttpOnly), not general client storage.
- Cache API: stores request/response pairs, mainly used by service workers for offline assets.
- Origin Private File System (OPFS): fast file storage for heavy apps (for example SQLite in the browser). Optional and advanced.
Practical concerns
- Storage can be cleared by the user or evicted under pressure; treat it as a cache unless you request persistence with
navigator.storage.persist(). navigator.storage.estimate()reports quota.- localStorage is synchronous: large reads block the main thread.
- Private browsing modes may limit or clear storage.
- Anything in storage is readable by any script on the origin, so never store secrets or long-lived tokens there.
- Sync between tabs with the
storageevent orBroadcastChannel. - Version your stored data so an app update can migrate old formats.
Good enough to move on
You can persist user preferences in localStorage with safe parsing, cache a list of records in IndexedDB with a wrapper library and explain why a JWT should not live in localStorage.
Key concepts
- localStorage and sessionStorage
- IndexedDB with idb or Dexie
- Cookies vs web storage
- Cache API
- Quotas, eviction and persistence
- Cross-tab sync with BroadcastChannel
- Origin Private File System
- Security of stored data
Mini project
Build a notes app that stores notes in IndexedDB (via Dexie), keeps UI preferences in localStorage, syncs changes across open tabs with BroadcastChannel and migrates an old storage format on startup.
Check yourself
Why is localStorage a poor choice for 20 MB of offline data, and what should you use instead?
Free resources
- Web Storage API (MDN)
- IndexedDB API (MDN)
- Storage for the web (web.dev)