HTML Web Storage
In this page:
What is Web Storage?
Web Storage is a standard browser API designed to save data locally as simple key-value pairs. It replaces traditional cookies for storing non-sensitive data, offering faster performance, better security, and a much larger storage capacity (up to 5MB).
Note: Only use web storage to save non-sensitive settings; never store sensitive data like passwords or credit card numbers.
Warning: Web storage data is saved as plain text inside the browser, making it accessible to anyone with access to the device.
Example: What is Web Storage?
<script>
localStorage.setItem('username', 'Alex');
</script>
Persistent Storage with localStorage
The localStorage object saves data persistently on the user's device. This data has no expiration date; it remains saved even when the user closes their tabs, restarts their browser, or shuts down their device.
Note: Use localStorage to save user preferences like dark mode settings so they persist across visits.
Warning: Avoid overusing localStorage as it can fill up the browser's storage quota if not managed.
Example: Persistent Storage with localStorage
<script>
localStorage.setItem('theme', 'dark');
console.log(localStorage.getItem('theme'));
</script>
Temporary Storage with sessionStorage
The sessionStorage object works exactly like localStorage, but it is temporary. The data is only saved for the duration of the page session, meaning it is deleted as soon as the user closes their browser tab.
Note: Use sessionStorage to store temporary form progress or single-session analytics data.
Warning: Data stored in sessionStorage will be lost if the user duplicates or closes the active tab.
Example: Temporary Storage with sessionStorage
<script>
sessionStorage.setItem('formProgress', 'step2');
console.log(sessionStorage.getItem('formProgress'));
</script>
Saving Structured Data using JSON
Web Storage can only store data as simple strings. To save complex data structures (like arrays or objects), you must convert them into a JSON string using JSON.stringify before saving, and parse them back using JSON.parse when retrieving.
Note: Use JSON encoding to save complex arrays of user settings or search histories in a single key.
Warning: Attempting to save raw JavaScript objects directly without converting them to JSON will result in saving an unreadable '[object Object]' string.
Example: Saving Structured Data using JSON
<script>
const settings = { theme: 'dark', fontSize: 16 };
localStorage.setItem('settings', JSON.stringify(settings));
const saved = JSON.parse(localStorage.getItem('settings'));
</script>
Clearing and Managing Storage Space
To keep your storage space organized and stay within browser limits, you should regularly clear out old or unused data. You can delete specific items using removeItem, or clear the entire storage area using the clear method.
Note: Provide a simple reset button on your page to let users clear their saved preferences easily.
Warning: Calling the clear method will delete all data stored by your website, so use it carefully.
Example: Clearing and Managing Storage Space
<script>
localStorage.removeItem('theme');
localStorage.clear();
</script>
Storage Limits Per Browser
Most modern browsers allow around 5 to 10 megabytes of storage per origin for both localStorage and sessionStorage, though the exact limit varies slightly between Chrome, Firefox, and Safari. This is plenty for settings and small cached data, but far too little for storing large files or media.
Note: For anything larger than a few megabytes, look into IndexedDB instead, which supports much larger storage quotas.
Warning: Exceeding the storage limit throws a QuotaExceededError, which will crash your script if you are not catching it.
Example: Storage Limits Per Browser
<script>
try {
localStorage.setItem('data', 'x'.repeat(10000000));
} catch (e) {
console.log('QuotaExceededError:', e.message);
}
</script>
Listening for Storage Events
The storage event fires on other open tabs or windows of the same site whenever localStorage changes in one of them, letting you keep multiple tabs in sync. Notably, this event does not fire in the same tab that made the change, only in other tabs listening to the same origin.
Note: Use the storage event to sync things like a logged-in state or shopping cart across multiple open tabs of your site instantly.
Warning: Because the storage event does not fire in the tab that made the change, you cannot use it to detect changes made by your own current tab's script.
Example: Listening for Storage Events
<script>
window.addEventListener('storage', function (event) {
console.log(event.key, event.newValue);
});
</script>
Cookies vs localStorage
Cookies are automatically sent to the server with every single HTTP request, have a much smaller size limit around 4 kilobytes, and can have an expiration date. localStorage never gets sent to the server automatically, holds far more data, and persists until explicitly cleared, making it much better suited for client-only data like UI preferences.
Note: Use cookies only for data the server genuinely needs to see, like authentication tokens, and use localStorage for everything that is purely for the browser's own use.
Warning: Storing sensitive data in localStorage is not inherently safer than cookies — both are readable by any JavaScript running on the page, so neither should hold plain sensitive secrets.
Example: Cookies vs localStorage
<script>
document.cookie = "token=abc123";
localStorage.setItem('uiTheme', 'dark');
</script>
- Storing sensitive user passwords or payment details in web storage, leaving them vulnerable to theft.
- Attempting to save raw JavaScript objects directly without converting them to JSON strings first.
- Exceeding the browser's 5MB storage limit, causing your save scripts to throw errors and fail.
- Web Storage allows websites to save data locally inside the user's browser as key-value pairs.
- Use localStorage to save persistent data that never expires, and sessionStorage for temporary, session-bound data.
- Convert complex data structures (like arrays or objects) to JSON strings before saving, and parse them back when retrieving.
Standard Web Storage APIs are supported natively by all modern web browsers.
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: