typeof localStorage is not a safe check

Evaluating the localStorage global throws when a visitor blocks site data, so the feature test itself fails. A one-line helper, applied to 990 pages.

Tools and projects · 1 min read · Source
software-engineeringci

Listen · 2:20 · read by a synthetic voice · Podcast

Feature-detecting storage with typeof localStorage === "undefined" feels defensive. It is not: when a visitor blocks site data, merely evaluating the localStorage global throws SecurityError, so the check itself is the thing that fails. The fix is a one-line helper that wraps the check in try.

We found the pattern in the usage counter copied into 990 calculator pages, fixed it in one pass, and added a CI check so new copies cannot reintroduce it. We reproduced the failure by simulating a throwing getter in node rather than in a real browser, so treat the user-visible effect (an uncaught error after the result renders) as likely, not observed. Details: the report.

More in Tools and projects

All writing · All in this topic · All tools and research