HTML Web Storage Tutorial
Learn how to use localStorage and sessionStorage to persist data in the browser
Introduction to Web Storage
The Web Storage API provides mechanisms for browsers to store key/value pairs in a much more intuitive fashion than using cookies. There are two main types of web storage:
localStorage
- Data persists even when the browser is closed and reopened
- Stored data has no expiration time
- Storage limit is typically 5MB per origin
- Accessible from any window/tab from the same origin
sessionStorage
- Data is cleared when the page session ends (when tab is closed)
- Useful for temporary data that shouldn't persist
- Storage limit is typically 5MB per origin
- Only accessible from the tab that created it
Basic localStorage Example:
Stored Value:
(empty)
Web Storage Examples
1. sessionStorage Example
Demonstrates how sessionStorage works (data is cleared when tab is closed)
Stored Value:
(empty)
2. Storing Complex Data
How to store and retrieve objects and arrays using JSON serialization
Stored Data:
(empty)
Advanced Web Storage Techniques
1. Storage Events
Listen for storage changes across browser tabs/windows
Event Log:
(no events yet)
2. Storage Limits and Quota
Understanding and handling storage limits
Storage Usage:
Could not calculate storage usage
Web Storage API Reference
Best Practices
1. Use JSON for Complex Data
Always serialize objects and arrays with JSON.stringify() before storing, and parse with JSON.parse() when retrieving.
2. Handle Storage Limits
Implement error handling for QuotaExceededError and consider periodically cleaning up old data.
3. Be Mindful of Sensitive Data
Never store sensitive information like passwords or tokens in web storage as it's accessible via JavaScript.
4. Choose the Right Storage Type
Use sessionStorage for temporary data that should disappear when the session ends, and localStorage for persistent data.
5. Implement Fallbacks
Provide fallback mechanisms for browsers that don't support web storage or when storage is disabled.
Conclusion
The Web Storage API provides a simple and effective way to persist data in the browser. With localStorage for long-term persistence and sessionStorage for session-based storage, you can enhance user experiences by maintaining state, preferences, and other data between page visits.