localStorage β Storing Data in the Browser
After completing this topic, you will be able to:
- Use localStorage
- Understand its limitations
- Determine what data should be stored
Data That Disappears When You Refresh
JavaScript variables disappear when you refresh the page. It's inconvenient if a user selects dark mode, but it reverts to light mode every time they refresh.
localStorage permanently stores data in the browser. It remains even after refreshing the page or closing the browser.
Basic Usage
// Store
localStorage.setItem("theme", "dark");
// Read
const theme = localStorage.getItem("theme"); // "dark"
// Delete
localStorage.removeItem("theme");
// Clear all
localStorage.clear();It stores data as key-value pairs. The value must be a string.
Objects as JSON
const user = { name: "Alice", age: 25 };
// Store β Convert the object to a string
localStorage.setItem("user", JSON.stringify(user));
// Read β Convert the string to an object
const saved = JSON.parse(localStorage.getItem("user"));
console.log(saved.name); // "Alice"Since localStorage only stores strings, you need to convert objects to strings using JSON.stringify before storing them. When reading, you need to restore them using JSON.parse.
If you directly store an object:
localStorage.setItem("user", { name: "Alice" });
localStorage.getItem("user"); // "[object Object]" β a useless stringlocalStorage vs sessionStorage
// localStorage β Permanent storage
localStorage.setItem("key", "value");
// sessionStorage β Deleted when the tab is closed
sessionStorage.setItem("key", "value");sessionStorage disappears when the browser tab is closed. It is not shared with other tabs of the same site. It is suitable for temporary data (e.g., backing up a form being filled out).
Things to Keep in Mind
Capacity Limit: Approximately 5MB per domain. This is sufficient for small settings, but do not store large amounts of data.
Only Strings Allowed: Numbers and booleans are also converted to strings.
localStorage.setItem("count", 42);
const count = localStorage.getItem("count"); // "42" (string)
const num = Number(count); // 42 (converted to a number)Do Not Store Sensitive Security Data: localStorage can be read by anyone using JavaScript. If you store passwords, tokens, or personal information, it can be stolen by XSS attacks.
Synchronous API: localStorage operates synchronously. Reading and writing large amounts of data can block the main thread.
Practical Use Cases
Suitable data: Theme settings, language settings, recent searches, shopping cart (for unauthenticated users), onboarding completion status.
Unsuitable data: Authentication tokens, passwords, user personal information, large amounts of data.
Key Takeaways
localStorage permanently stores key-value strings in the browser. Objects are handled by converting them to strings using
JSON.stringify/JSON.parse. Never store sensitive security data.