How to use the Storage API for client-side data

· Category: JavaScript

Short answer

Use localStorage for persistent key-value strings, sessionStorage for tab-scoped data, and IndexedDB for structured, large-scale client-side storage. All are subject to same-origin policy and quota limits.

Details

localStorage and sessionStorage are simple synchronous APIs with about 5-10 MB limits. They only store strings, so objects must be serialized with JSON.stringify. IndexedDB is asynchronous, transactional, and supports indexing and large binary data. The Storage API also includes StorageManager for estimating available quota.

Security is critical: never store sensitive tokens in localStorage because it is vulnerable to XSS. Use HttpOnly cookies instead for authentication data. If you are building a Node.js backend to sync this data, see How to implement JWT authentication in Node.js for secure session management.

Tips

  • Always wrap localStorage access in try/catch because writes throw when storage is full or disabled.
  • Use storage events to synchronize tabs via localStorage changes.
  • For handling the asynchronous nature of IndexedDB, review how to use async/await to avoid callback pyramids.