The HTML Web Storage API provides localStorage, a key-value store built into the browser that keeps data even after the visitor closes the tab or restarts their computer. Developers use localStorage to remember UI preferences like dark mode, collapsed sidebars, or draft form text.
localStorage stores every key and value strictly as strings per origin (protocol + domain + port). Four methods cover everyday usage:
localStorage.setItem(key, value): Saves or overwrites a string value.localStorage.getItem(key): Retrieves the saved string, or null if the key does not exist.localStorage.removeItem(key): Deletes a single entry.localStorage.clear(): Wipes every entry stored for your site origin.When storing objects or arrays, convert them with JSON.stringify() before saving and JSON.parse() when reading them back.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Local Storage Demo</title>
</head>
<body style="font-family: system-ui, sans-serif; padding: 20px;">
<label for="theme-select">Preferred Theme:</label>
<select id="theme-select">
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<p id="saved-status"></p>
<script>
const select = document.getElementById('theme-select');
const status = document.getElementById('saved-status');
const savedTheme = localStorage.getItem('user_theme') || 'light';
select.value = savedTheme;
status.textContent = `Loaded saved theme: ${savedTheme}`;
select.addEventListener('change', () => {
localStorage.setItem('user_theme', select.value);
status.textContent = `Saved theme: ${select.value}`;
});
</script>
</body>
</html>
Browsers typically allocate around 5 MB per origin for localStorage, and all calls run synchronously on the main thread. Never store passwords, credit card numbers, or sensitive secrets in localStorage, because any script running on your page (including XSS injections) can read it immediately.
JSON.stringify(): Saving false turns into the string "false", which is truthy in JavaScript if checks.JSON.parse() without try/catch: Corrupted storage values throw a SyntaxError and crash your script if not guarded.localStorage as a replacement for server databases: Browser storage clears whenever users wipe site data or switch devices.localStorage holds around 5 MB purely on the client without being sent on every HTTP request, whereas cookies hold ~4 KB and travel to the server automatically with requests.
No. Storage is scoped strictly by origin, so http://example.com and https://example.com get separate stores.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.