localStorage, sessionStorage and Cookies in JavaScript

Web apps remember things between page loads: a login session, items in a cart, a dark-mode setting, a dismissed cookie banner. They store that data in the browser with localStorage, sessionStorage and cookies. Testers deal with all three constantly: a test that passes alone but fails after another test often shares stale storage, and the fastest way to log in or skip an onboarding tour in a test is to set the right storage values directly. In this lesson you will use the Web Storage API, save objects as JSON, read and write cookies with their attributes, understand which data JavaScript cannot see (HttpOnly), and use storage to set up test state. All examples ran in Chrome on http://localhost:5500.

Advertisement

📖 What You’ll Learn: what browser storage is, the localStorage API (setItem, getItem, removeItem, clear, key, length), storing objects and arrays with JSON, sessionStorage and how it differs, storage limits and errors, the storage event, reading and writing cookies with document.cookie, cookie attributes (max-age, expires, path, SameSite, Secure, HttpOnly), deleting cookies, a comparison of all three, security rules, and how tests use storage.


🗄️ Storage in the Browser

localStoragesessionStorageCookies
LifetimeUntil deletedUntil the tab is closedUntil expiry (or the session)
ScopeSame origin, all tabsSame origin, this tab onlyDomain and path you choose
SizeAbout 5 MB per originAbout 5 MB per originAbout 4 KB per cookie
Sent to the server?NoNoYes, with every matching request
Readable by JavaScript?YesYesYes, unless HttpOnly
Typical usePreferences, cached data, draftsOne-tab wizard stateLogin sessions, tracking, consent

An origin is scheme + host + port, for example https://sqatools.in. Storage is separated per origin: http://localhost:5500 and http://localhost:3000 have different localStorage.

💡 Tip: See and edit all of it in DevTools → Application → Storage: Local Storage, Session Storage and Cookies for the current site. It is the quickest way to inspect app state during exploratory testing.


💾 localStorage Basics

localStorage stores string key–value pairs that survive reloads and browser restarts:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>

  <script src="app.js"></script>
</body>
</html>

📄 app.js

localStorage.setItem("theme", "dark");
localStorage.setItem("fontSize", 16);           // stored as the string "16"

console.log(localStorage.getItem("theme"));
console.log(localStorage.getItem("fontSize"), typeof localStorage.getItem("fontSize"));
console.log(localStorage.getItem("missing"));   // unknown key -> null
console.log("items:", localStorage.length, "| first key:", localStorage.key(0));

localStorage.removeItem("fontSize");
console.log(Object.keys(localStorage));

localStorage.clear();                           // remove everything for this origin
console.log("after clear:", localStorage.length);

🖥️ Browser console

dark
16 string
null
items: 2 | first key: theme
["theme"]
after clear: 0
MethodDoes
setItem(key, value)Save (value converted to a string)
getItem(key)Read; null if missing
removeItem(key)Delete one key
clear()Delete all keys for this origin
key(i), lengthLoop over keys

🧩 Storing Objects and Arrays with JSON

Because values are strings, objects must be converted with JSON.stringify and read back with JSON.parse. Forgetting this is a classic bug:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>

  <script src="app.js"></script>
</body>
</html>

📄 app.js

const cart = [{ sku: "KB-01", qty: 1 }, { sku: "MS-02", qty: 2 }];

localStorage.setItem("cartWrong", cart);                  // bug: becomes "[object Object],[object Object]"
console.log(localStorage.getItem("cartWrong"));

localStorage.setItem("cart", JSON.stringify(cart));
const saved = JSON.parse(localStorage.getItem("cart"));
console.log(saved.length, "items, first:", saved[0].sku);

// safe read helper with a default value
function load(key, fallback) {
  try {
    return JSON.parse(localStorage.getItem(key)) ?? fallback;
  } catch {
    return fallback;                                       // corrupted value
  }
}
localStorage.setItem("settings", "{broken json");
console.log(load("settings", { theme: "light" }));
console.log(load("never-saved", []));

🖥️ Browser console

[object Object],[object Object]
2 items, first: KB-01
{"theme":"light"}
[]

🪟 sessionStorage

sessionStorage has the same API, but data belongs to one tab and is deleted when that tab closes. A page reload keeps it. A tab that the user opens independently (new tab, typed URL) starts with empty sessionStorage. A tab opened by the page with window.open starts with a copy, and from then on the two are independent, while localStorage is always shared:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>

  <script type="module" src="app.js"></script>
</body>
</html>

📄 app.js

localStorage.setItem("visits", "1");
sessionStorage.setItem("checkoutStep", "2");

const child = window.open(location.href + "?tab=2");        // a second tab, same origin
await new Promise((resolve) => child.addEventListener("load", resolve));
console.log("child sessionStorage (copied when opened):", child.sessionStorage.getItem("checkoutStep"));

sessionStorage.setItem("checkoutStep", "3");                // change both in THIS tab
localStorage.setItem("visits", "2");
console.log("child step after change:", child.sessionStorage.getItem("checkoutStep"));
console.log("child visits after change:", child.localStorage.getItem("visits"));
child.close();

🖥️ Browser console

child sessionStorage (copied when opened): 2
child step after change: 2
child visits after change: 2

📌 Note: Never rely on sessionStorage to share data between tabs: whether a new tab gets a copy depends on how it was opened. Use localStorage (with the storage event) or the server for that.


Advertisement

⚠️ Limits, Errors and the storage Event

Each origin gets roughly 5 MB. Exceeding it throws a QuotaExceededError, so wrap large writes in try...catch:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>

  <script src="app.js"></script>
</body>
</html>

📄 app.js

const oneMB = "x".repeat(1024 * 1024);
let saved = 0;
try {
  for (let i = 0; i < 20; i++) {
    localStorage.setItem(`chunk${i}`, oneMB);
    saved++;
  }
} catch (e) {
  console.log(`${e.name} after ${saved} MB`);
}
localStorage.clear();

🖥️ Browser console

QuotaExceededError after 4 MB

When one tab changes localStorage, every other tab of the same origin receives a storage event. Apps use it to log the user out everywhere or sync a cart:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>

  <script type="module" src="app.js"></script>
</body>
</html>

📄 app.js

const other = window.open(location.href + "?tab=2");
await new Promise((resolve) => other.addEventListener("load", resolve));

other.addEventListener("storage", (e) => {
  console.log(`other tab saw: ${e.key} changed from ${e.oldValue} to ${e.newValue}`);
});

localStorage.setItem("loggedIn", "true");
localStorage.setItem("loggedIn", "false");      // e.g. user logged out in this tab
await new Promise((r) => setTimeout(r, 100));
other.close();

🖥️ Browser console

other tab saw: loggedIn changed from null to true
other tab saw: loggedIn changed from true to false

🍪 Cookies with document.cookie

document.cookie is an odd API: reading it returns all visible cookies as one string, "a=1; b=2"; assigning to it adds or updates a single cookie, without removing the others:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>

  <script src="app.js"></script>
</body>
</html>

📄 app.js

document.cookie = "theme=dark";
document.cookie = "lang=en-IN; max-age=86400; path=/";        // expires in 1 day
document.cookie = `lastSearch=${encodeURIComponent("usb cable & hub")}; path=/`;

console.log(document.cookie);

// parse into an object
const cookies = Object.fromEntries(
  document.cookie.split("; ").map((pair) => {
    const [name, ...rest] = pair.split("=");
    return [name, decodeURIComponent(rest.join("="))];
  })
);
console.log(cookies);

// delete by setting an expiry in the past (same path!)
document.cookie = "theme=; max-age=0";
console.log(document.cookie);

🖥️ Browser console

theme=dark; lang=en-IN; lastSearch=usb%20cable%20%26%20hub
{"theme":"dark","lang":"en-IN","lastSearch":"usb cable & hub"}
lang=en-IN; lastSearch=usb%20cable%20%26%20hub
AttributeMeaning
max-age=seconds / expires=dateWhen the cookie expires; without either it is a session cookie
path=/Which URL paths receive the cookie (default: the current path’s folder)
domain=example.comShare with subdomains
SecureOnly sent over HTTPS (and localhost)
SameSite=Lax | Strict | NoneWhether the cookie is sent on cross-site requests (CSRF protection); Lax is the browser default
HttpOnlySet only by the server; JavaScript cannot read it
Advertisement

HttpOnly cookies are invisible to JavaScript

Here the server sets two cookies, one with HttpOnly. The browser sends both back to the server, but document.cookie only shows the other one:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>

  <script type="module" src="app.js"></script>
</body>
</html>

📄 app.js

const res = await fetch("/api/login");                 // our test server sets cookies here
console.log("document.cookie:", document.cookie);

🖥️ Browser console

document.cookie: ui_lang=en

Login session cookies should always be HttpOnly, so that an XSS bug cannot steal them. That is also why a test cannot read a session token with document.cookie; use the automation tool’s cookie API (Playwright: context.cookies()) instead.


🔐 Security Rules

  • Never store passwords in any browser storage.
  • Any script on the page, including a third-party script or an XSS payload, can read localStorage. Prefer HttpOnly, Secure, SameSite cookies for session tokens.
  • Do not trust storage values: users can edit them in DevTools. Validate on the server, and parse defensively in the client.
  • Clear user data on logout: remove keys, and expire cookies on the server.

⚠️ Watch out: A good negative test: log in, copy a localStorage or cookie value, log out, put the value back and reload. If you are logged in again, the server did not invalidate the session.


🧪 Tester Scenario: Setting Up State Through Storage

Many apps decide what to show from storage: feature flags, a “tour seen” flag, a consent choice or a saved cart. Setting these before the page loads skips slow UI steps and makes tests deterministic:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>
  <div id="tour" hidden>Welcome tour (step 1 of 5)</div>
  <div id="banner" hidden>We use cookies. <button>Accept</button></div>
  <p id="cart">Cart: 0</p>
  <script src="app.js"></script>
</body>
</html>

🧪 Test setup (runs before the page’s own code)

localStorage.setItem("tourSeen", "true");
localStorage.setItem("cart", JSON.stringify([{ sku: "KB-01" }, { sku: "MS-02" }]));
document.cookie = "consent=accepted; path=/";

📄 app.js

// --- the app's startup code ---
const state = {
  tourSeen: localStorage.getItem("tourSeen") === "true",
  consent: document.cookie.includes("consent=accepted"),
  cart: JSON.parse(localStorage.getItem("cart") ?? "[]"),
};
document.querySelector("#tour").hidden = state.tourSeen;
document.querySelector("#banner").hidden = state.consent;
document.querySelector("#cart").textContent = `Cart: ${state.cart.length}`;

console.log("tour visible:", !document.querySelector("#tour").hidden);
console.log("cookie banner visible:", !document.querySelector("#banner").hidden);
console.log(document.querySelector("#cart").textContent);

🖥️ Browser console (test state was set before the page loaded)

tour visible: false
cookie banner visible: false
Cart: 2

The test arranged the state before the app’s code ran, so the page opened with the tour and banner hidden and two items in the cart. In Playwright the same is done with page.addInitScript() for localStorage and context.addCookies() for cookies, and storageState saves and restores a whole logged-in state (cookies plus localStorage) between tests.

📄 storage.spec.js (Playwright)

// Playwright: arrange storage before the app loads
await context.addCookies([{ name: "consent", value: "accepted", url: "http://localhost:5500" }]);
await page.addInitScript(() => {
  localStorage.setItem("tourSeen", "true");
});
await page.goto("/");
await expect(page.getByText("Welcome tour")).toBeHidden();

Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Save the username “asha” in localStorage, read it back and then delete it.

Show answer

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>

  <script src="app.js"></script>
</body>
</html>

📄 app.js

localStorage.setItem("username", "asha");
console.log(localStorage.getItem("username"));
localStorage.removeItem("username");
console.log(localStorage.getItem("username"));

🖥️ Browser console

asha
null

Q2. Store the settings object { theme: "dark", pageSize: 20 } and read pageSize back as a number.

Show answer

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>

  <script src="app.js"></script>
</body>
</html>

📄 app.js

localStorage.setItem("settings", JSON.stringify({ theme: "dark", pageSize: 20 }));
const settings = JSON.parse(localStorage.getItem("settings"));
console.log(settings.pageSize, typeof settings.pageSize);

🖥️ Browser console

20 number

Q3. Count how many times the page has been loaded using localStorage.

Show answer

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>

  <script src="app.js"></script>
</body>
</html>

📄 app.js

const visits = Number(localStorage.getItem("visits") ?? 0) + 1;
localStorage.setItem("visits", visits);
console.log(`You have visited this page ${visits} time(s).`);

🖥️ Browser console (first load)

You have visited this page 1 time(s).

Q4. Write getCookie(name) that returns a cookie’s decoded value or null.

Show answer

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>

  <script src="app.js"></script>
</body>
</html>

📄 app.js

function getCookie(name) {
  const pair = document.cookie.split("; ").find((c) => c.startsWith(name + "="));
  return pair ? decodeURIComponent(pair.slice(name.length + 1)) : null;
}
document.cookie = "city=" + encodeURIComponent("New Delhi");
console.log(getCookie("city"), getCookie("missing"));

🖥️ Browser console

New Delhi null

Q5. Set a cookie promo=SQA10 that expires in 7 days, then delete it.

Show answer

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
</head>
<body>

  <script src="app.js"></script>
</body>
</html>

📄 app.js

document.cookie = `promo=SQA10; max-age=${7 * 24 * 60 * 60}; path=/`;
console.log(document.cookie);
document.cookie = "promo=; max-age=0; path=/";
console.log(JSON.stringify(document.cookie));

🖥️ Browser console

promo=SQA10
""

Q6. A test passes when run alone but fails when run after the “add to cart” test. What storage-related cause would you check first?

Show answer

Shared state: the earlier test left a cart in localStorage or a cookie, so the later test starts with items it did not expect. Make tests independent by using a fresh browser context per test (Playwright does this by default), clearing storage in setup, or setting exactly the state each test needs.


🧠 MCQ Quiz: localStorage and Cookies

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What type are values stored in localStorage?
  2. What does localStorage.getItem("missing") return?
  3. When is sessionStorage cleared?
  4. Which storage is automatically sent to the server with requests?
  5. What does document.cookie = "a=1" do to existing cookies?
  6. How do you delete a cookie from JavaScript?
  7. Why can JavaScript not read an HttpOnly cookie?
  8. What happens when localStorage is full?
  9. Which event tells other tabs that localStorage changed?
  10. Where is the safest place for a login session token?

💼 Interview Questions and Answers

Q1. localStorage vs sessionStorage vs cookies?

localStorage persists until cleared and is shared by all tabs of an origin; sessionStorage lives for one tab (a tab opened with window.open starts with a copy); both hold about 5 MB, are only accessible from JavaScript and are never sent to the server automatically. Cookies are small (about 4 KB), have expiry, path, domain and SameSite controls, are sent with every matching HTTP request, and can be made HttpOnly so scripts cannot read them, which makes them the right place for session identifiers.

Q2. How do you avoid logging in through the UI in every test?

Log in once (through the UI or the API), save the resulting cookies and localStorage, and load them in each test. Playwright’s storageState does exactly this, typically in a setup project. Alternatively call the login API and add the returned cookie with context.addCookies. Keep one UI login test so the login page itself stays covered.

Q3. What storage-related checks belong in a test plan?

Data survives reload (localStorage) or not (sessionStorage); logout clears user data and invalidates server sessions; session cookies are HttpOnly, Secure and SameSite; tampered or corrupted values are handled gracefully; the app copes with storage being full or disabled (private mode); and data from one user is never visible to the next user on the same browser.

Q4. Why do tests become flaky because of storage, and how do you prevent it?

Tests that share a browser profile inherit each other’s storage: a leftover cart, a cached feature flag or an old session changes what the next test sees, and results depend on test order. Use a fresh browser context per test, clear storage in setup, set the exact state each test needs, and avoid running tests against a shared real user account in parallel.


Advertisement

❓ Frequently Asked Questions

🤔 Is localStorage shared between http and https?

No. http://site.com and https://site.com are different origins with separate storage.

🤔 Does localStorage work in private or incognito windows?

Yes, but it is deleted when the private window is closed. Some browsers give private windows a smaller quota.

🤔 Can I store images or files in localStorage?

Only as strings (for example base64), which is inefficient and quickly hits the limit. Use IndexedDB or the Cache API for larger or binary data.

🤔 What is IndexedDB?

A larger, asynchronous browser database for structured data and files, used by offline-capable apps. It is more complex than localStorage; libraries such as idb make it easier.


🏁 Summary

  • localStorage keeps strings per origin until cleared; sessionStorage keeps them for one tab.
  • Store objects with JSON.stringify, read them with JSON.parse and a safe default.
  • document.cookie reads all visible cookies and writes one at a time; use max-age, path, SameSite and Secure.
  • HttpOnly cookies are invisible to JavaScript: the right place for session tokens; never store passwords.
  • In tests, set storage and cookies to arrange state quickly, and isolate tests so storage does not leak between them.

Next, continue with Lesson 61: Browser APIs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in