Local Storage is a feature of the Web Storage API that allows websites to store key-value pairs in a web browser, persisting even after the browser is closed. It is an ideal solution for storing small amounts of data that should remain available across sessions.
Unlike cookies, data stored in Local Storage is not sent with every HTTP request, making it more efficient for storing client-side data such as theme preferences, UI settings, or a shopping cart between visits.
What You’ll Learn
01
setItem
Save strings.
02
getItem
Read values.
03
removeItem
Delete one key.
04
clear
Wipe all data.
05
JSON
Store objects.
06
Limits
Size & security.
Fundamentals
What Is Local Storage?
Local Storage is a part of the browser’s Web Storage API that allows you to store data locally on the user’s computer.
Data stored in Local Storage does not expire unless explicitly removed, making it persistent even when the browser or device is restarted.
It stores data as key-value pairs and is particularly useful for saving user preferences, theme settings, or lightweight app state across visits.
💡
Beginner Tip
Think of localStorage as a simple notepad tied to your website’s domain. Every page on example.com can read and write the same keys.
Features
Key Features of Local Storage
Key-Value Storage — stores data as simple key-value pairs.
Persistent Storage — data remains available across browser sessions.
Synchronous API — all operations are synchronous, unlike IndexedDB.
Limited Size — each domain can typically store up to 5 MB of data.
No Expiration — data persists until manually deleted by the application or the user.
API
How to Use Local Storage
Local Storage is easy to use with JavaScript. You interact with it using the localStorage object, which provides methods to store, retrieve, and remove data. The data is stored as strings, so you need to stringify objects before storing them.
The four essential methods mirror sessionStorage:
localStorage.setItem(key, value) — save a string
localStorage.getItem(key) — read a string (or null)
localStorage.removeItem(key) — delete one entry
localStorage.clear() — delete every key for this origin
Write
Setting Data in Local Storage
To store data in Local Storage, you can use the setItem method. Here’s how you can store a simple key-value pair:
js
localStorage.setItem('username', 'JohnDoe');
You can also store objects, but since Local Storage only stores strings, you’ll need to use JSON.stringify:
js
var user = { name: 'JohnDoe', age: 30 };
localStorage.setItem('user', JSON.stringify(user));
Read
Retrieving Data from Local Storage
To retrieve data, use the getItem method:
js
var username = localStorage.getItem('username');
console.log(username); // JohnDoe
If you are retrieving an object, you will need to parse it back into its original form using JSON.parse:
js
var user = JSON.parse(localStorage.getItem('user'));
console.log(user.name); // JohnDoe
Delete
Removing Data from Local Storage
If you want to remove a specific item from Local Storage, use the removeItem method:
js
localStorage.removeItem('username');
Reset
All Data in Local Storage
You can clear all the data stored in Local Storage for your domain by using the clear method:
js
localStorage.clear();
Use clear() carefully—it removes every key your site saved on this origin, not just one feature’s data.
Watch Out
Limitations of Local Storage
Size Limit — the amount of data you can store is limited (typically around 5 MB per domain).
Synchronous API — all Local Storage operations are blocking, which may impact performance if used improperly on large values.
Security Risks — data stored in Local Storage is not encrypted, so sensitive information should not be stored.
Same-Origin Policy — Local Storage data is accessible only within the same domain and protocol.
Compare
localStorage vs sessionStorage
Feature
localStorage
sessionStorage
Lifetime
Until cleared manually
Until tab closes
Shared across tabs
Yes (same origin)
No (per tab)
Survives browser restart
Yes
No
Typical use
Theme, prefs, cart
Wizard step, tab draft
Cheat Sheet
⚡ Quick Reference
Task
Code
Save
localStorage.setItem('key', 'value')
Read
localStorage.getItem('key')
Delete one
localStorage.removeItem('key')
Delete all
localStorage.clear()
Count keys
localStorage.length
Store object
setItem('k', JSON.stringify(obj))
Hands-On
Examples Gallery
Five short examples from basic save/read to a full page with four buttons. Try It Yourself demos use plain HTML with no CSS.
Example 1 — Save and Read a String
js
localStorage.setItem('username', 'JohnDoe');
var name = localStorage.getItem('username');
console.log(name); // JohnDoe
Reload the Try It page after saving—the name remains until you clear localStorage.
Example 2 — Store an Object with JSON
js
var user = { name: 'Jane', theme: 'dark' };
localStorage.setItem('user', JSON.stringify(user));
var loaded = JSON.parse(localStorage.getItem('user'));
console.log(loaded.theme); // dark
Close the browser and reopen—greeting is still there until you Remove or Clear.
Applications
🚀 Common Use Cases
Theme mode — dark/light preference across visits.
Language or locale — remember UI language choice.
Shopping cart — hold items between sessions (not for payment secrets).
Form drafts — autosave long comments or blog posts.
Onboarding flags — “has seen tutorial” toggle.
Cross-tab sync — listen for the storage event when another tab writes.
🧠 How localStorage Works (Step by Step)
1
Page calls setItem
JavaScript writes a string under a key for this origin.
Write
2
Browser persists data
Stored on disk per origin (protocol + host + port).
Save
3
Any tab on same site
All tabs share the same localStorage keys.
Share
4
Later visit: getItem
Page reads saved values on load.
Read
=
💾
Until cleared
Data survives reloads, restarts, and new tabs.
Compatibility
Universal Browser Support
localStorage is supported in all modern browsers, including Chrome, Firefox, Safari, and Edge. It is part of the HTML5 Web Storage specification.
✓ Baseline · Since HTML
localStorage API
localStorage is supported in all modern browsers, including Chrome, Firefox, Safari, and Edge. It is part of the HTML5 Web Storage specification.
98%Modern browser support
Google ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
localStorage APIExcellent
Bottom line: Safe to use in all current projects. Feature-detect with typeof localStorage !== 'undefined' in very old environments.
Pro Tips
💡 Best Practices
✅ Do
Use localStorage for small, non-sensitive preferences
Serialize objects with JSON.stringify / JSON.parse
Pick clear key names (theme, cartItems)
Remove keys when data is no longer needed
Handle null from getItem before using values
Use the storage event for cross-tab updates
❌ Don’t
Store passwords, tokens, or PCI data
Assume unlimited space (stay under ~5 MB)
Store huge JSON blobs (use IndexedDB instead)
Trust localStorage values without validation
Block the main thread with massive synchronous writes
Use localStorage when tab-only data is enough (use sessionStorage)
Wrap Up
Conclusion
HTML Local Storage is an easy-to-use and efficient way to store data on the client side. It is perfect for saving small amounts of persistent data without relying on external databases or cookies.
However, it’s important to be mindful of its limitations, especially when dealing with sensitive information and large datasets. For tab-scoped data, see Session Storage. For structured offline data, see IndexedDB.
Use these points when picking client-side storage.
5
Core concepts
💾01
Persistent
Survives restarts.
Lifetime
🔗02
Shared tabs
Same origin.
Scope
📝03
Strings
JSON helps.
Type
📈04
~5 MB
Per origin.
Limit
🔒05
Not secure
No secrets.
Safety
❓ Frequently Asked Questions
localStorage is part of the Web Storage API. It stores key-value string pairs in the browser for the current origin. Data persists after the tab or browser is closed until you remove it or the user clears site data.
localStorage is shared across all tabs on the same origin and lasts until cleared. sessionStorage is scoped to one tab and is deleted when that tab closes.
Call localStorage.setItem('key', 'value'). Both key and value must be strings. Retrieve with localStorage.getItem('key'), which returns null if the key does not exist.
Only strings are stored directly. Serialize objects with JSON.stringify(obj) before setItem, and parse with JSON.parse(localStorage.getItem('key')) when reading.
No. Unlike cookies, localStorage data stays in the browser and is not included in HTTP requests. That makes it more efficient for client-only preferences.
Browsers typically allow about 5 MB per origin for localStorage. Storing very large strings may throw a QuotaExceededError.
Did you know?
When one tab changes localStorage, other tabs on the same origin receive a storage event. That is a simple way to sync theme or logout state across tabs without WebSockets.