localStorage in JavaScript: Saving Data in the Browser
Learn how to use localStorage in JavaScript to save and retrieve data in the browser without a server. Covers setItem, getItem, JSON storage, and when to use sessionStorage instead.
localStorage in JavaScript lets you save data directly in the user’s browser — no server, no database. It persists between sessions, meaning the data is still there after the user closes and reopens the browser. It’s perfect for saving preferences, themes, shopping carts, and small amounts of state.
The Basic API
localStorage has a simple key-value API:
// Save data
localStorage.setItem("username", "kaikobud");
localStorage.setItem("theme", "dark");
// Read data
const username = localStorage.getItem("username");
console.log(username); // "kaikobud"
// Delete one item
localStorage.removeItem("theme");
// Clear everything
localStorage.clear();
All values are stored as strings. That’s an important limitation to understand.
Storing Objects with JSON
Since localStorage only stores strings, use JSON.stringify and JSON.parse for objects:
const user = { name: "Kaikobud", role: "admin", age: 28 };
// Store the object
localStorage.setItem("user", JSON.stringify(user));
// Retrieve it
const stored = localStorage.getItem("user");
const parsedUser = JSON.parse(stored);
console.log(parsedUser.name); // "Kaikobud"
Always wrap JSON.parse in a try/catch — if the stored value is corrupted, it will throw:
function getStoredUser() {
try {
return JSON.parse(localStorage.getItem("user"));
} catch {
return null;
}
}
localStorage vs sessionStorage
| Feature | localStorage | sessionStorage |
|---|---|---|
| Persists after tab close | Yes | No |
| Shared across tabs | Yes | No |
| Max storage | ~5–10MB | ~5–10MB |
Use sessionStorage for data that should only last the current browser session, like temporary form state.
A Practical Example: Dark Mode Toggle
const toggle = document.querySelector("#theme-toggle");
const saved = localStorage.getItem("theme") || "light";
document.body.dataset.theme = saved;
toggle.addEventListener("click", () => {
const current = document.body.dataset.theme;
const next = current === "dark" ? "light" : "dark";
document.body.dataset.theme = next;
localStorage.setItem("theme", next);
});
Conclusion
localStorage in JavaScript is one of the quickest ways to add persistence to a frontend app. Use it for preferences, settings, and small data — but not for sensitive data like tokens (sessionStorage or HttpOnly cookies are better choices). Combine it with JSON serialization and you can store almost anything.
Read next: JavaScript Event Listeners
External resource: MDN — Window.localStorage
Related Articles
async/await in JavaScript: Making Async Code Readable
Learn how async/await in JavaScript works with clear examples. Understand how it replaces Promise chains, handles errors with try/catch, and makes asynchronous code easier to read.
How to Write Clean Functions in JavaScript
Learn how to write clean JavaScript functions that are easy to read, test, and maintain. This guide covers naming, single responsibility, pure functions, and avoiding common pitfalls.
CSS Flexbox in Plain English: A Beginner's Guide
Learn CSS Flexbox with simple, visual explanations. This guide covers display flex, justify-content, align-items, flex-wrap, and practical layouts every developer needs to know.