Skip to content

Intermediate · JavaScript in the browser: DOM and events · topic 39 of 64 · 25 min

Saving data in the browser

Explanation

localStorage keeps small pieces of text in the browser, even after it is closed. sessionStorage is the same but is cleared when the tab closes. Both store only strings, so you save objects with JSON.stringify and read them with JSON.parse. Use them for things like a theme or a cart, never for passwords or login tokens.

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.

Think of it like this: localStorage is like a cupboard in your own home: what you keep there stays until you take it out. sessionStorage is like a locker at a railway station cloakroom: it is emptied when you leave (close the tab). Cookies are like a token you show at the counter every time you visit.
localStoragesessionStorageCookies
How long it lastsUntil code or the user clears itUntil the tab is closedUntil its expiry date
SizeAbout 5 MB per siteAbout 5 MB per siteAbout 4 KB each
Sent to the server?NoNoYes, with every request
Good forTheme, language, cartSteps of a form in one tabLogin sessions (set by the server)
javascript
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 closes
setItem saves, getItem reads (null if missing), removeItem deletes

Storing 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.

javascript
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
  }
}
Save with JSON.stringify; read with JSON.parse inside try/catch
Tip: Always have a default. getItem returns null the first time, and the saved text may be broken or from an old version of your site. try/catch and ?? keep the page working.

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.
Careful: Never store passwords, OTPs, card details or valuable login tokens in localStorage. Any script running on your page can read it, so one XSS bug would leak everything. Logins should use cookies that the server marks HttpOnly, which JavaScript cannot read.

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

javascript
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
});
The theme choice is still there tomorrow
Tip: Open DevTools, go to the Application panel (Storage in Firefox), and choose Local Storage. You can see, edit and delete every saved key there while you test.

Watch the lesson

Saving data in the browser · 1/7

localStorage

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)

Task 1 · Code · Javascript

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.

Task 2 · Code · Javascript

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).

Task 3 · Practice

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

Question 1

1.What type of values does localStorage keep?

Question 2

2.Which storage is emptied when the user closes the tab?

Question 3

3.What is the right way to save an array called cart?

Question 4

4.Which of these should never be stored in localStorage?

Question 5

5.What does localStorage.getItem('pincode') return when nothing was saved under that key?

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.

← Previous: Timers: running code later