Local storage and session storage
Course contents (16 lessons)
- Modern syntax
- Destructuring, spread and rest
- ES modules: import and export
- Objects, this and errors
- Classes and prototypes
- Understanding this in JavaScript
- Error handling: try, catch and custom errors
- Asynchronous JavaScript
- The event loop: how JavaScript handles waiting
- From callbacks to promises to async/await
- Fetch and REST APIs
- Working in the browser
- Local storage and session storage
- Debugging with browser DevTools
- Performance basics: debounce and throttle
- Node.js essentials
- Node.js and npm basics
- Working with files in Node.js
- A tiny HTTP server with Node.js
- Testing and the final project
- Testing basics with the Node.js test runner
- Final project: a post explorer with modules and fetch
Remembering things
Variables disappear when the page reloads. For small bits of data that should survive, such as a theme choice, a draft or a to-do list, the browser gives you the Web Storage API. It has two parts with the same methods.
localStoragekeeps data until the user or your code clears it. It survives closing the browser.sessionStoragekeeps data for one tab. It is cleared when the tab closes.
Data is stored per origin, that is, per combination of protocol, domain and port. https://example.com cannot read what https://other.com stored.
The basic methods
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");
console.log(theme); // "dark"
console.log(localStorage.getItem("missing")); // null
localStorage.removeItem("theme");
localStorage.clear(); // remove everything for this origin
console.log(localStorage.length);
Keys and values are both strings. getItem returns null when the key does not exist. If you store a number, you get a string back:
localStorage.setItem("visits", 5);
console.log(localStorage.getItem("visits")); // "5"
console.log(typeof localStorage.getItem("visits")); // "string"
Storing objects and arrays
Convert them to JSON text on the way in, and parse on the way out:
const settings = { theme: "dark", fontSize: 18, tags: ["js", "web"] };
localStorage.setItem("settings", JSON.stringify(settings));
const loaded = JSON.parse(localStorage.getItem("settings"));
console.log(loaded.tags[0]); // "js"
If you try localStorage.setItem("settings", settings) without stringify, JavaScript stores "[object Object]", which is useless. This mistake is very common.
A safe wrapper
Reading storage can fail. The value might not exist, the text might be damaged, or the browser might block storage in private mode. A small wrapper makes everything simpler:
const storage = {
get(key, fallback = null) {
try {
const raw = localStorage.getItem(key);
return raw === null ? fallback : JSON.parse(raw);
} catch {
return fallback;
}
},
set(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
return true;
} catch {
return false; // storage full or blocked
}
},
remove(key) {
try { localStorage.removeItem(key); } catch {}
},
};
storage.set("favourites", [3, 7, 12]);
console.log(storage.get("favourites", [])); // [3, 7, 12]
console.log(storage.get("unknown", [])); // []
The code that uses the wrapper never has to think about null, JSON.parse errors, or exceptions. I put this in a storage.js module in most small projects.
Example: remember a theme
const button = document.querySelector("#theme-toggle");
function applyTheme(theme) {
document.body.dataset.theme = theme;
storage.set("theme", theme);
}
applyTheme(storage.get("theme", "light"));
button.addEventListener("click", () => {
const next = document.body.dataset.theme === "dark" ? "light" : "dark";
applyTheme(next);
});
On load we apply the saved theme or "light". Each click flips it and saves it. In the CSS, you can style [data-theme="dark"].
Listening for changes in other tabs
When another tab of the same site changes localStorage, your tab gets a storage event:
window.addEventListener("storage", event => {
if (event.key === "theme") applyTheme(event.newValue.replace(/"/g, ""));
});
It does not fire in the tab that made the change. It is useful for keeping a logged-in state in sync across tabs.
Limits you should know
- About 5 MB per origin, depending on the browser. Do not store large data.
- Everything is synchronous. Writing a lot of data blocks the page.
- Only strings. Binary data needs encoding.
- Data can be cleared by the user at any time. Never treat it as permanent.
- For larger or structured data, look at IndexedDB. For files, the Cache API or the File System Access API.
Security: do not store secrets
Any script running on your page can read localStorage. If your site has a cross-site scripting bug, an attacker can steal everything in it. So:
- Never store passwords, payment details or private data.
- Be careful with authentication tokens. Many security teams prefer
HttpOnlycookies for session tokens, because JavaScript cannot read those. - Treat everything you read from storage as untrusted input. Someone can edit it in DevTools. Validate it and use
textContentwhen displaying it.
Common mistakes
- Forgetting to stringify objects. You end up with
[object Object]. - Not parsing on the way out. You get text and not an array.
- No fallback for null.
JSON.parse(null)returnsnull, and then.lengthfails. - Storing too much. Quotas are small.
- Using it for secrets. Do not.
- Assuming the data is valid. An older version of your app may have saved a different shape.
Try it yourself
- Build a counter that saves its value in
localStorage, so reloading the page keeps the number. - Add a dark mode toggle that remembers the choice.
- Save a form draft on every
inputevent and restore it on page load. - Open DevTools, go to Application and then Local Storage, find your keys and edit one by hand. See what your app does.
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");
console.log(theme); // "dark"
console.log(localStorage.getItem("missing")); // null
localStorage.removeItem("theme");
localStorage.clear(); // remove everything for this origin
console.log(localStorage.length);
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account