Web Storage
Master localStorage, sessionStorage, and IndexedDB to build fast, offline-friendly applications with persistent client-side data.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
🎯 What You'll Learn
💡 Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:
- Download Node.js to run JavaScript on your computer
- Use your browser ' s Developer Console (Press F12) to test code snippets
- Create a .html file with <script> tags and open it in your browser
Understanding the Storage Landscape
JavaScript provides three powerful storage mechanisms, each designed for different needs:
localStorage
- • Persists forever
- • Shared across tabs
- • ~5-10 MB limit
- • Synchronous
sessionStorage
- • Deleted when tab closes
- • Isolated per tab
IndexedDB
- • Stores objects & blobs
- • Hundreds of MB+
- • Asynchronous
localStorage: Long-Term Persistent Storage
localStorage keeps data forever (or until the user clears it manually). It's ideal for preferences, themes, cached data, and recently viewed items.
Common Mistakes to Avoid
sessionStorage: Tab-Specific, Temporary Storage
sessionStorage is deleted when the tab closes. It's perfect for multi-step forms, temporary shopping cart state, and tab-isolated workflows.
localStorage vs sessionStorage
Feature
localStorage
sessionStorage
Persistence
Until cleared
Until tab closes
Scope
Shared across tabs
Per-tab isolation
Use case
Preferences & saved state
In-progress workflows
Building a Storage Service Layer
Production apps don't store values directly into localStorage. They create a Storage Service Layer that centralizes logic, handles parsing errors, and adds features like namespacing.
TTL-Based Storage (Time-To-Live)
For caching API responses, you want data to expire automatically. This pattern prevents stale data while improving performance.
IndexedDB: The Browser's Real Database
IndexedDB is the production-grade solution for storing large datasets and offline application data. It supports images, audio files, documents, and complex object structures.
Opening a Database
CRUD Operations
Storing Files and Blobs
IndexedDB can store images, audio, PDFs, and binary data — essential for PWAs and offline apps.
Checking Storage Availability
Important: Safari Private Mode often breaks IndexedDB entirely. Always build with fallbacks!
Cross-Tab Communication
localStorage can act as a lightweight messaging system between tabs. Changes trigger events in other tabs automatically.
Offline-First Architecture
This is the architecture behind modern productivity apps like Notion, Slack, and Linear. Save locally first, sync when online.
Hybrid Storage Architecture
Professional apps combine all three storage types based on data characteristics:
Performance Best Practices
Safe JSON Parsing
Always wrap JSON.parse in try-catch to prevent app crashes from corrupted data.
Common Mistakes Developers Make
❌ Security Mistakes
- • Storing passwords in localStorage
- • Storing JWT tokens (XSS can steal them)
- • Storing PII or banking data
❌ Performance Mistakes
- • Storing huge arrays in localStorage
- • Writing on every keystroke
- • Loading large storage synchronously
❌ Logic Mistakes
- • Forgetting to JSON.stringify objects
- • Assuming storage always exists
- • Not handling quota errors
✔ Best Practices
- • Use storage service layers
- • Check storage availability first
- • Use IndexedDB for large data
Practice Exercises
- A theme switcher using localStorage
- A multi-step checkout using sessionStorage
- A fully offline notes app using IndexedDB
- A custom wrapper library that unifies all three storage types
- A cache system that stores API responses with TTL
- An IndexedDB migration (version 1 → 2 → 3)
- A "Recently Viewed Items" tracker
- Cross-tab real-time sync for a shopping cart
What You Learned
- ✔ localStorage for persistent settings
- ✔ sessionStorage for tab-specific state
- ✔ IndexedDB for large datasets
- ✔ Building storage service layers
- ✔ TTL-based caching patterns
- ✔ Cross-tab communication
- ✔ Offline-first sync architecture
- ✔ Hybrid storage design
- ✔ Storing files and blobs
- ✔ Safe JSON parsing
🎉 Lesson Complete!
You now understand how to store data client-side using localStorage, sessionStorage, and IndexedDB. Next up: Building Custom APIs.
Practice quiz
How long does data in localStorage persist?
- Until the tab closes
- For one hour
- Forever, until manually cleared
- Until the page reloads
Answer: Forever, until manually cleared. localStorage persists indefinitely until the user or code clears it; sessionStorage clears on tab close.
When is sessionStorage data deleted?
- When the tab closes
- After 24 hours
- Never automatically
- On every reload
Answer: When the tab closes. sessionStorage is wiped when the tab closes, making it ideal for tab-specific, temporary state.
How is sessionStorage scoped across browser tabs?
- Shared across all tabs
- Shared only within the same domain
- Shared with incognito tabs
- Isolated per tab
Answer: Isolated per tab. Each tab has its own separate sessionStorage; localStorage is shared across tabs of the same origin.
What type are values returned by localStorage.getItem?
- Always the original object
- Always strings
- Numbers when numeric
- null for objects
Answer: Always strings. Web Storage values are always strings; you must JSON.parse objects and Number() numeric values.
What is logged? localStorage.setItem('count', 1); console.log(localStorage.getItem('count') + 1);
- '11'
- 2
- 11
- It throws
Answer: '11'. getItem returns the string '1', so '1' + 1 is string concatenation giving '11'. Convert with Number() first.
How should you store an object in localStorage?
- Pass it directly to setItem
- Use localStorage.setObject
- JSON.stringify it before setItem
- Spread it into setItem
Answer: JSON.stringify it before setItem. Storing an object directly yields '[object Object]'; use JSON.stringify on save and JSON.parse on read.
Which storage type is async, event-based, and handles large data and blobs?
- localStorage
- IndexedDB
- sessionStorage
- Cookies
Answer: IndexedDB. IndexedDB is asynchronous and built for large datasets, objects, and files; Web Storage is synchronous and small.
Roughly how much can localStorage typically hold?
- About 4 KB
- Several GB
- Unlimited
- About 5-10 MB
Answer: About 5-10 MB. localStorage and sessionStorage are limited to roughly 5-10 MB; cookies are ~4 KB; IndexedDB can hold GBs.
Which event lets one tab detect a localStorage change made in another tab?
- The 'change' event
- The 'storage' event
- The 'message' event
- The 'sync' event
Answer: The 'storage' event. Writing to localStorage fires a 'storage' event in other tabs, enabling lightweight cross-tab communication.
Why should JSON.parse on stored data be wrapped in try/catch?
- To speed it up
- Because parse is async
- To prevent crashes from corrupted or invalid JSON
- To stringify the result
Answer: To prevent crashes from corrupted or invalid JSON. Corrupted stored data can make JSON.parse throw; a safe parser catches it and returns a fallback.
Continue this course
- Previous: Advanced Fetch Patterns
- Next: Building Custom APIs