Skip to content
engineering workbench.by StudyPort Academy
All errors
browser · DEBUG LIBRARY

localStorage value is a string, or storage throws

Locate the failed assumption, reproduce it, then repair the cause.

What actually caused it

localStorage and sessionStorage store strings only, scoped to the origin. A number written with setItem is converted to text. Reading it back and adding 1 concatenates instead of doing arithmetic. .parse then throws if the text is not JSON, and JSON.stringify is required when you meant to store an .

Storage is also and can throw: private browsing, a disabled storage policy, or a full quota. It is not sent with requests, so the server never sees it unless you send it yourself. It is a poor place for secrets. Anyone with script access on the page can read it.

sessionStorage dies with the tab. localStorage stays until it is cleared. Neither one is a cache you can trust to exist, and neither one replaces a server check of a form.

Minimal reproduction

A number that comes back as text

localStorage.setItem("visits", 2);
const visits = localStorage.getItem("visits") + 1;
console.log(visits);

The log is 21, because "2" + 1 concatenates.

The fix

Convert on the way in and the way out. Store String(value) or .stringify(value), and read with an explicit conversion such as Number or JSON.parse inside try/catch. If storage throws, continue without it.

Keep passwords and session secrets out of web storage. Prefer an HttpOnly cookie set by the server when the browser should not read the credential. Treat stored form drafts as a convenience copy, and validate the submitted value on the server anyway.

Convert before arithmetic

localStorage.setItem("visits", "2");
const stored = localStorage.getItem("visits");
const visits = Number(stored) + 1;
console.log(visits);

Number("2") is 2, so the next visit is 3.

Survive storage being unavailable

function readVisits() {
  try {
    return Number(localStorage.getItem("visits")) || 0;
  } catch {
    return 0;
  }
}
console.log(readVisits());