The Web Storage API lets JavaScript persist string data directly in the browser, surviving page refreshes without a server or database. This lesson covers the difference between permanent localStorage and per-tab sessionStorage, serializing objects with JSON.stringify/JSON.parse since storage only holds strings, removing data, storage size limits, security considerations, and the cross-tab storage event.
1JavaScript Web Storage API | LocalStorage & SessionStorage - In-Depth Guide Part 1
Welcome to JavaScript Web Storage. Normally, when you refresh a page, all your variables are lost. Web Storage allows you to persist data locally in the user browser, creating a 'Memory' for your app.
// Web Storage: Persistence for the Modern Web2JavaScript Web Storage API | LocalStorage & SessionStorage - In-Depth Guide Part 2
There are two types: localStorage and sessionStorage. localStorage is permanentāit stays there even if the user closes the tab or restarts their computer.
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');3JavaScript Web Storage API | LocalStorage & SessionStorage - In-Depth Guide Part 3
sessionStorage is temporary. It works exactly like localStorage, but the data is wiped automatically as soon as the user closes the specific browser tab.
sessionStorage.setItem('tempID', '12345');4JavaScript Web Storage API | LocalStorage & SessionStorage - In-Depth Guide Part 4
Crucial Rule: Web Storage only saves Strings. If you try to save an object directly, it will be converted to the useless string [object Object]'.
const user = { name: 'Neo' };
localStorage.setItem('user', user); // ā Wrong!5JavaScript Web Storage API | LocalStorage & SessionStorage - In-Depth Guide Part 5
To store objects, you must ''Serialize' them into a JSON string using JSON.stringify(). When you retrieve them, 'Deserialize' back with JSON.parse().
localStorage.setItem('user', JSON.stringify(user)); // ā
Correct
const data = JSON.parse(localStorage.getItem('user'));6JavaScript Web Storage API | LocalStorage & SessionStorage - In-Depth Guide Part 6
Removing data: Use .removeItem('key') to delete a specific item, or .clear() to wipe EVERYTHING from that storage domain.
localStorage.removeItem('theme');
localStorage.clear();7JavaScript Web Storage API | LocalStorage & SessionStorage - In-Depth Guide Part 7
Watch the render. See the ''Storage' panel of the browser tools update as we programmatically save, update, and delete persistent user preferences.
/* Storage Lab: Browser Persistence Rendered */8JavaScript Web Storage API | LocalStorage & SessionStorage - In-Depth Guide Part 8
Security Note: Never store sensitive information like passwords or private API keys in Web Storage. It is easily accessible by any script running on the page.
// ā ļø SECURITY WARNING ā ļø
// No Passwords in LocalStorage!9JavaScript Web Storage API | LocalStorage & SessionStorage - In-Depth Guide Part 9
Storage Limits: Most browsers allow around 5MB of data per domain. This is plenty for settings and small lists, but not for large files or videos.
// Capacity: ~5MB10JavaScript Web Storage API | LocalStorage & SessionStorage - In-Depth Guide Part 10
Events: You can even listen for the storage' event to react when data is changed in another tab of your same website!
window.addEventListener('storage', (e) => {
console.log('Storage updated in another tab!');
});11JavaScript Web Storage API | LocalStorage & SessionStorage - In-Depth Guide Part 11
You' Your applications can now remember their users, preferences, and progress across sessions.
console.log('Persistence Layer: Online');12JavaScript Web Storage API | LocalStorage & SessionStorage - In-Depth Guide Part 12
Storage mastery achieved! Now let's dive into the powerful world of Asynchronous JavaScript.
/* Next: Asynchronous JS & Promises */13Step-by-Step Breakdown
Welcome to JavaScript Web Storage. Normally, when you refresh a page, all your variables are lost. Web Storage allows you to persist data locally in the user browser, creating a 'Memory' for your app.
There are two types: localStorage and sessionStorage. localStorage is permanentāit stays there even if the user closes the tab or restarts their computer.
sessionStorage is temporary. It works exactly like localStorage, but the data is wiped automatically as soon as the user closes the specific browser tab.
Checkpoint: Which storage type persists even after the browser tab is closed and reopened?
- ālocalStorage
- āsessionStorage
Crucial Rule: Web Storage only saves Strings. If you try to save an object directly, it will be converted to the useless string [object Object]'.
To store objects, you must ''Serialize' them into a JSON string using JSON.stringify(). When you retrieve them, 'Deserialize' back with JSON.parse().
Removing data: Use .removeItem('key') to delete a specific item, or .clear() to wipe EVERYTHING from that storage domain.
Watch the render. See the ''Storage' panel of the browser tools update as we programmatically save, update, and delete persistent user preferences.
Checkpoint: What happens if you try to save a JavaScript Object directly into localStorage without using JSON.stringify?
- āIt throws a fatal error
- āIt saves the string '[object Object]'
Security Note: Never store sensitive information like passwords or private API keys in Web Storage. It is easily accessible by any script running on the page.
Storage Limits: Most browsers allow around 5MB of data per domain. This is plenty for settings and small lists, but not for large files or videos.
Events: You can even listen for the storage' event to react when data is changed in another tab of your same website!
You' Your applications can now remember their users, preferences, and progress across sessions.
Checkpoint: Which method should you use to retrieve a value that was previously saved in localStorage?
- āfindItem
- āgetItem
Storage mastery achieved! Now let's dive into the powerful world of Asynchronous JavaScript.
Level Up š
Advanced cheat sheets, SEO tricks, and interview prep for this topic.
Browser Support
Fully supported.
Fully supported.
Fully supported.
Fully supported.
Accessibility (A11y)
1Persist User Accessibility Preferences Like Reduced Motion or Font Size Overrides
If your site lets users toggle accessibility-related settings (larger text, reduced motion, high contrast), save that choice in localStorage and re-apply it on every page load ā silently resetting a user's chosen accommodation on every visit is a real usability barrier.
SEO Implications
- 1
Storing SEO-Relevant Content Only in localStorage Hides It from Search Engines
Content written to localStorage and rendered client-side after the fact isn't present in the server-rendered HTML a crawler typically evaluates, so anything meant to be indexed (page text, product data) needs to be part of the actual rendered markup, not something only assembled from client-side storage after load.
Best Practices
Wrap Storage Access in Try/Catch and Feature-Detect Availability
localStorage can throw (e.g. in Safari private browsing mode, or when a quota is exceeded) instead of failing silently ā wrap reads and writes in try/catch, and treat storage as an enhancement your app can function without, not a hard dependency.
Namespace and Version Your Storage Keys
Prefixing keys (e.g. 'myApp:v2:userPrefs') avoids collisions with other scripts or older versions of your own app sharing the same domain, and makes it easy to detect and migrate or discard stale data formats when your storage schema changes.
Frequent Bugs
localStorage.getItem() returns the string 'null' instead of an actual null value when a key doesn't exist and was previously stored with JSON.stringify(null).
getItem() returns the literal string 'null' if 'null' was ever explicitly stored as a value, versus an actual null if the key was never set at all. Always check `localStorage.getItem(key) !== null` before calling JSON.parse, and be aware JSON.parse('null') legitimately returns the JS value null.
Data saved with localStorage.setItem(key, someObject) comes back as the string '[object Object]' when read later.
Web Storage only stores strings, so passing an object directly gets silently coerced with .toString(), producing the useless '[object Object]'. Always JSON.stringify() an object before saving it, and JSON.parse() the result when reading it back.
Real-World Examples
Persisting a User's Theme Preference Across Sessions
A web app needed to remember whether a user had chosen dark or light mode, applying it immediately on every future visit without waiting for a server round-trip.
function saveTheme(theme) {
localStorage.setItem('app:theme', theme);
}
function loadTheme() {
return localStorage.getItem('app:theme') || 'light';
}
document.documentElement.dataset.theme = loadTheme();