Skip to content

JavaScript Tutorial Browser Storage

Storage Limits and When Not to Use localStorage

Lesson 138 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

localStorage is simple, which makes it tempting to use for everything. Know its limits.

Practical limits

  • Size: about 5 MB per origin in most browsers. Exceeding it throws a QuotaExceededError.
  • Strings only. Everything needs converting.
  • Synchronous. It blocks the main thread, so large reads and writes slow the page.
  • No expiry. Data stays forever unless you delete it or the user clears it.
  • Per origin. Not shared across subdomains or protocols.
  • User-controlled. Visitors can clear it or change it in developer tools, and some browsers limit or clear it automatically in private modes or after a time of inactivity.
script.js
JS
function trySave(key, value) {
  try {
    localStorage.setItem(key, value);
    return "saved";
  } catch (error) {
    return "failed: " + error.name;
  }
}

console.log(trySave("note", "hello")); // → saved

Always handle the failure case when losing the data would hurt the user.

Never store secrets

This is the most important rule. localStorage is not a safe place for passwords, access tokens, API keys, personal data or anything sensitive.

  • Any JavaScript on your page can read it, including a malicious script injected through an XSS attack or a compromised third-party script.
  • It is stored unencrypted on the visitor’s device.

For login sessions, servers normally use cookies marked HttpOnly (which JavaScript cannot read), Secure and SameSite. Use the approach recommended by your platform, rather than saving tokens yourself in localStorage.

Also not suitable for

  • Large or structured data. Use IndexedDB, the browser’s real database.
  • Data the server needs. It is not sent automatically. Use cookies or requests.
  • Anything important that must not be lost. It is only a cache on one device. Save important data on a server.
  • Sharing between devices. It stays on one browser.

Good uses

  • Interface preferences (theme, language, layout).
  • Draft text and unsent form data.
  • Small flags such as “dismissed the banner”.
  • A cache of non-sensitive public data.

Alternatives at a glance

NeedUse
Small preferenceslocalStorage
Per-tab temporary datasessionStorage
Login sessionsserver-managed cookies
Large or structured offline dataIndexedDB
Data in the URL, shareablequery string (URLSearchParams)
dangerous
Treat all stored data as untrusted
Users can edit it. When you read it back, validate it as you would any input, and never use it to make security decisions.