HTML Web Storage
Web Storage lets a page save key/value strings on the user's device. There are two variants: localStorage persists forever; sessionStorage lasts until the tab closes.
localStorage vs sessionStorage
| localStorage | sessionStorage | |
|---|---|---|
| Lives until | Cleared by user or your code. | The tab closes. |
| Shared across tabs? | Yes (same origin). | No — per tab. |
| Capacity | ~5–10 MB per origin. | Same. |
| Sent with requests? | No — purely client-side. | No. |
The API (same for both)
// Strings only
localStorage.setItem('user', 'ada');
const u = localStorage.getItem('user');
// Save an object — JSON-encode first
localStorage.setItem('prefs', JSON.stringify({ theme: 'dark' }));
const p = JSON.parse(localStorage.getItem('prefs') || '{}');
// Clean up
localStorage.removeItem('user');
localStorage.clear();
Note: Web Storage stores plain text. Never put passwords, tokens, or other sensitive data in it — any script running on the page can read everything.
Tip: For larger or structured data, use IndexedDB instead. The iwantcoding.com progress tracker uses
localStorage — check the sidebar to see it in action.Example
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Web Storage</title>
</head>
<body>
<h1>HTML Web Storage</h1>
<p>This is a demo page for the "HTML Web Storage" lesson.</p>
</body>
</html>
Try it Yourself »
Exercise
Store a value in localStorage with the correct method.
localStorage.
('theme', 'dark');
Two words camelCased.
Discussion
Loading…