Intermediate · JavaScript in the browser: DOM and events · topic 39 of 64 · 25 min
Saving data in the browser
Explanation
Remembering things in the browser
Web Storage lets a page save small pieces of data in the browser as key and value pairs. A key is a name, like "theme", and a value is the text saved under it, like "dark". There are two kinds: localStorage and sessionStorage.
| localStorage | sessionStorage | Cookies | |
|---|---|---|---|
| How long it lasts | Until code or the user clears it | Until the tab is closed | Until its expiry date |
| Size | About 5 MB per site | About 5 MB per site | About 4 KB each |
| Sent to the server? | No | No | Yes, with every request |
| Good for | Theme, language, cart | Steps of a form in one tab | Login sessions (set by the server) |
localStorage.setItem('city', 'Pune');
console.log(localStorage.getItem('city')); // 'Pune'
console.log(localStorage.getItem('pincode')); // null (nothing saved)
localStorage.removeItem('city');
sessionStorage.setItem('step', '2'); // gone when the tab closesStoring objects and arrays with JSON
Storage keeps only strings. If you save the number 5, you get back "5". If you save an array directly, you get the useless text "[object Object]". JSON (JavaScript Object Notation) is a text format for data: JSON.stringify turns an object into text, and JSON.parse turns it back.
const cart = [{ id: 'p1', name: 'Rice 5 kg', qty: 2 }];
localStorage.setItem('cart', JSON.stringify(cart));
function loadCart() {
try {
return JSON.parse(localStorage.getItem('cart')) ?? [];
} catch {
return []; // the saved text was broken
}
}Limits to remember
- Size: about 5 MB per site. Fine for settings, not for photos or videos.
- Only strings: use JSON for anything else.
- Same origin only: a page can read only the storage of its own origin (protocol + domain + port).
- The user can clear it at any time, and private windows forget it on close. Never keep the only copy of important data there.
- It is synchronous (the page waits while it reads), so keep the data small.
Cookies, briefly
A cookie is a small piece of text the browser stores and sends back to the server with every request. Servers use cookies to remember that you are logged in. You will rarely write cookies by hand in front-end code; the server sets them, and options like HttpOnly, Secure and SameSite keep them safe.
Example: remembering dark mode
const toggle = document.querySelector('#theme-toggle');
const root = document.documentElement;
root.dataset.theme = localStorage.getItem('theme') ?? 'light';
toggle.addEventListener('click', () => {
const next = root.dataset.theme === 'dark' ? 'light' : 'dark';
root.dataset.theme = next; // CSS uses [data-theme=dark]
localStorage.setItem('theme', next); // remember the choice
});Watch the lesson
Saving data in the browser · 1/7
Websites can remember small things, like your theme or your cart, even after you close the browser.
Prefer a video by a teacher? Find free videos on “javascript localStorage sessionStorage json tutorial for beginners” on YouTube ↗
In real life: A kirana shop cart that survives a reload
On a local grocery delivery site, you add rice, dal and oil to the cart, then your phone network drops and the page reloads. Because the cart was saved in localStorage as JSON after each change, the page reads it back with JSON.parse and your three items are still there. Your login, though, is kept in a secure HttpOnly cookie set by the server, not in localStorage.
Practice (0/3 done)
Write two functions. saveTheme(storage, theme) saves theme under the key "theme" with storage.setItem. loadTheme(storage) returns the saved theme if it is "dark" or "light", and returns "light" when nothing (null) or anything else is saved. In the browser you would pass localStorage; the tests pass a fake storage object.
Write saveCart(storage, cart) and loadCart(storage). saveCart stores the cart array under the key "cart" as a JSON string. loadCart reads it back as an array. loadCart must return [] when nothing is saved or when the saved text is broken (use try/catch around JSON.parse).
Add a dark mode button to one of your earlier pages. Clicking it switches a data-theme attribute on <html> between "light" and "dark", and your CSS changes colours with a [data-theme="dark"] selector. Save the choice in localStorage and apply it when the page loads. Then open DevTools > Application > Local Storage and watch the value change.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.