The HTML Web Storage API's localStorage object allows web applications to store key-value data pairs directly in the user's web browser with no expiration date, keeping data intact even after closing browser tabs or restarting the browser.
Data in localStorage is stored as text strings and accessed via window.localStorage:
// Save item to localStorage
localStorage.setItem("theme", "dark");
// Read item from localStorage
const theme = localStorage.getItem("theme");
// Remove single item
localStorage.removeItem("theme");
// Clear all localStorage data
localStorage.clear();
Key localStorage properties:
JSON.stringify() before saving and parsed back using JSON.parse().flowchart TD
A["Web Storage Choice"] --> B["localStorage (Permanent Storage)"]
A --> C["sessionStorage (Temporary Session Storage)"]
B --> B1["Persists across browser restarts & tab closes (5MB limit)"]
C --> C1["Clears automatically when browser tab closes (5MB limit)"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML LocalStorage Example</title>
</head>
<body style="font-family: system-ui, sans-serif; background-color: #0f172a; color: #f8fafc; padding: 2rem;">
<h2>User Preferences Storage</h2>
<div style="background-color: #1e293b; padding: 1.5rem; border-radius: 8px; max-width: 400px;">
<label for="username" style="display: block; margin-bottom: 0.5rem;">Saved Username:</label>
<input type="text" id="username" style="width: 100%; padding: 8px; border-radius: 4px; border: 1px solid #334155; margin-bottom: 1rem;">
<button id="save-btn" style="background-color: #2563eb; color: white; padding: 8px 14px; border: none; border-radius: 4px; cursor: pointer;">
Save Username
</button>
</div>
<script>
const input = document.getElementById("username");
const btn = document.getElementById("save-btn");
// Load saved username on startup
input.value = localStorage.getItem("saved_user") || "";
btn.addEventListener("click", () => {
localStorage.setItem("saved_user", input.value);
alert("Username saved locally!");
});
</script>
</body>
</html>
localStorage: Data in localStorage is accessible to client-side JavaScript and vulnerable to Cross-Site Scripting (XSS) attacks. Use HttpOnly cookies for auth tokens.JSON.stringify() for objects and arrays: Always serialize complex object data structures (localStorage.setItem('user', JSON.stringify(userObject))).try...catch blocks to handle browser private browsing mode storage restrictions gracefully.Write a JavaScript line saving an object { theme: "dark", lang: "en" } to localStorage using JSON.stringify()!
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.
You've completed this section! Take a quick 5-question quiz to check your understanding.