Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk3 min

How to Catch localStorage Errors and Keep Your App Working

The localStorage getter can throw before a method call, and setItem() can fail when a value cannot be stored. Protect both operations and provide a usable fallback.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Wrap both access to window.localStorage and each storage operation in try...catch. The property getter can throw before a method runs, and setItem() can fail when a value cannot be stored. Treat persistence as optional where possible, and keep the current page usable with in-memory or default state if saving fails.

Why localStorage can throw

There are two distinct failure points: obtaining the storage object and using it. The WHATWG HTML Standard’s Web Storage section says the localStorage getter throws SecurityError when the document has an opaque origin or a policy decision disallows persistence. MDN’s localStorage reference notes examples such as invalid schemes, including file: and data:, and browser settings that block persistence.

As an Amazon Associate I earn from qualifying purchases.

A successful getter does not guarantee every later operation will succeed. The standard says Storage.setItem() throws QuotaExceededError if the new value cannot be set. Disabled site storage and exhausted available space are possible causes; the exception name alone does not establish which one occurred.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Protect the getter and storage calls

Keep the property access inside the try block. A helper can return null when storage cannot be obtained:

function getLocalStorage() {
  try {
    return window.localStorage;
  } catch {
    return null;
  }
}

Then handle the write itself too. A getter that succeeds does not guarantee that setItem() will:

function savePreference(key, value) {
  try {
    window.localStorage.setItem(key, value);
    return true;
  } catch (error) {
    // Keep the current application usable without persisted state.
    return false;
  }
}

Callers should use the return value rather than reporting that a preference was saved unconditionally. If remembering the value matters to the user, show a concise notice or offer a meaningful alternative; otherwise continue with the current in-memory value or a default.

Handle SecurityError by checking the page context

When obtaining window.localStorage fails, inspect the actual page context rather than assuming the storage methods are at fault:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Confirm the document’s origin and whether it is served over HTTP or HTTPS. The two protocols have separate localStorage areas, so data saved under one is not the same area as data under the other.
  • Check whether the page is in a sandboxed or opaque-origin context, or whether browser policy or user settings prohibit persistence.
  • If the page uses a file: URL, do not rely on consistent behavior: the standard leaves that case undefined and browsers may differ.

Do not make weakening privacy settings the default fix. Your application should remain understandable and usable when browser policy prevents persistence.

Handle QuotaExceededError without destructive recovery

A write failure means the requested value was not stored; it does not, by itself, prove that storage is full. MDN’s availability example recognizes that QuotaExceededError can also occur when storage is effectively unavailable. Avoid assuming a universal localStorage size limit: the standard specifies the exception, not a fixed cross-browser quota.

  • Keep a working in-memory or default value so the current interaction can continue.
  • Reduce unnecessary stored data when that is appropriate for the application.
  • If offering deletion or a retry, explain what will be removed and get the user’s consent where appropriate.
  • Do not automatically call localStorage.clear() just to make room. The standard defines it as removing all key/value pairs, which may erase unrelated application data.

Probe availability only when you need to

MDN documents an availability check that obtains the storage object, writes a temporary key, and removes it inside protected error handling. If you adapt that approach, use a collision-resistant temporary key and ensure cleanup. A probe is itself a write to the user’s storage area, so prefer handling the real operation when a separate test would not change the application’s behavior.

Do not infer availability solely from the presence of window.localStorage: the getter may throw, and a later write may still fail. If using MDN’s probe logic, its example treats QuotaExceededError as evidence of availability only when stored data already exists.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose storage based on the job

localStorage is synchronous: reads, writes, and removals block JavaScript execution while they run. It suits small, infrequent preferences better than large, frequent, or structured workloads. For those, consult MDN’s Web Storage API guidance and current browser guidance on other storage APIs, quotas, and eviction.

Ordinary localStorage data persists across browser sessions, but private-session data is cleared when the last private tab closes, and browser policy can prevent persistence. Make the fallback match what the user expects: a preference can often remain active for the current session even if it cannot be remembered, while a feature that genuinely depends on saved data needs a clear failure path.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.