Skip to content
Browser & DOMChapter 41 / 47Beginner5 min read

localStorage, sessionStorage & Cookies

Learn how to save data in the browser with JavaScript localStorage and sessionStorage, store objects with JSON, and how they differ from cookies.

On this page

1. What is web storage?

localStorage data stays even after you close the browser. sessionStorage data lasts only as long as that tab is open. Close the tab and the data is gone.

Cookies are also stored in the browser, but they are sent to the server automatically with every request. That is why login sessions often live in cookies.

2. Why does it matter?

If the user's theme, cart or form draft disappears on every reload, the experience is bad. With storage, the browser remembers small things for you.

Without storageWith storage
Dark mode goes back to light on reloadThe theme is remembered
The form draft is lostThe draft comes back
Every small setting goes to the serverSmall settings stay in the browser
Log in again on every pageThe session continues through a cookie

3. Where is it used?

DataBetter place
Theme, languagelocalStorage
Guest cartlocalStorage
A multi-step form in one tabsessionStorage
Login sessionHttpOnly cookie (set by the server)
Large data, offline appIndexedDB
FeaturelocalStoragesessionStorageCookies
How longUntil deletedUntil the tab closesUntil Expires / Max-Age
SizeAbout 5 MBAbout 5 MBAbout 4 KB
Sent to the serverNoNoWith every request
Readable from JavaScriptYesYesOnly if not HttpOnly

4. How does it work?

Saving and loading an object
A JavaScript object
Turn it into a string with JSON.stringify
Save it with localStorage.setItem
After a reload, get the string with getItem
Turn it back into an object with JSON.parse

Storage is per origin, which means another site cannot read the data of https://site.com.

5. Code example

Remembering the theme

js
const saved = localStorage.getItem("theme") ?? "light";
document.body.dataset.theme = saved;

themeBtn.addEventListener("click", () => {
  const next = document.body.dataset.theme === "dark" ? "light" : "dark";
  document.body.dataset.theme = next;
  localStorage.setItem("theme", next);
});

Safe helpers for objects

js
function save(key, value) {
  try {
    localStorage.setItem(key, JSON.stringify(value));
  } catch (error) {
    console.warn("Could not save:", error.name);
  }
}

function load(key, fallback) {
  try {
    const raw = localStorage.getItem(key);
    return raw === null ? fallback : JSON.parse(raw);
  } catch {
    return fallback;
  }
}

save("cart", [{ id: 7, qty: 2 }]);
console.log(load("cart", []));

sessionStorage.setItem("step", "2");
localStorage.removeItem("cart");
js
document.cookie = "lang=en; Max-Age=2592000; Path=/; SameSite=Lax; Secure";
console.log(document.cookie);

How does the code work?

LineWhat happens
getItem("theme") ?? "light"It is null on the first visit, so the default is used
JSON.stringify(value)Turned the object into a string
try / catchErrors can happen when storage is full or in private mode
JSON.parse(raw)Turns the string back into an object
removeItem("cart")Deletes one key
document.cookie = ...Sets one cookie for 30 days

Interview tip

Keeping an auth token in localStorage is risky, because any script can read it if XSS happens. For sessions, a server-set cookie with HttpOnly, Secure and SameSite is better.

6. Common mistakes

Mistake: Passing an object straight to setItem

Why? It turns into the string [object Object] and the data is lost.

Better: Save with JSON.stringify and load with JSON.parse.

Mistake: Keeping passwords or tokens in localStorage

Why? Every script running on the page, including XSS, can read this data.

Better: Keep sensitive session data in an HttpOnly cookie, set by the server.

Mistake: Calling JSON.parse without try

Why? With corrupted or old data, a SyntaxError crashes the page.

Better: Keep a try catch and a fallback value in the load helper.

Mistake: Treating storage like a database

Why? It has a 5 MB limit, the user can clear it any time, and it works synchronously.

Better: Use storage for small settings, and the server or IndexedDB for large data.

7. What to learn before and after

Suggested order
JSON
DOM Events
Forms and Validation
Web Storage

Final quick revision

PointDetail
localStorageStays forever, until deleted
sessionStorageOnly for that tab
CookiesSent to the server with every request, small size
Strings onlyUse JSON for objects
MethodssetItem, getItem, removeItem, clear
SecurityNo secrets in storage, use an HttpOnly cookie