Skip to content
Latchkey

Jest "SecurityError: localStorage is not available"

jsdom refuses localStorage/sessionStorage access when the document origin is "opaque" - the default about:blank. The spec forbids storage on opaque origins, so jsdom throws a SecurityError.

What this error means

Any code touching localStorage under jsdom throws SecurityError: localStorage is not available for opaque origins. It is deterministic and tied to the jsdom URL, not to the test logic.

Jest output
SecurityError: localStorage is not available for opaque origins

    at Window.get localStorage (node_modules/jsdom/lib/jsdom/browser/Window.js)

Common causes

Default opaque jsdom origin

With no configured URL, jsdom runs at about:blank, an opaque origin. Per the HTML storage spec, localStorage on an opaque origin must throw.

No storage mock provided

If you do not give jsdom a real http(s) origin, you must instead stub localStorage yourself; otherwise every access errors.

How to fix it

Give jsdom a concrete origin

Set a real URL so the origin is no longer opaque and storage works.

jest.config.js
// jest.config.js
module.exports = {
  testEnvironment: 'jsdom',
  testEnvironmentOptions: { url: 'http://localhost/' },
};

Mock storage in setup

jest.setup.js
// jest.setup.js
const store = {};
global.localStorage = {
  getItem: (k) => store[k] ?? null,
  setItem: (k, v) => { store[k] = String(v); },
  removeItem: (k) => { delete store[k]; },
  clear: () => { for (const k in store) delete store[k]; },
};

How to prevent it

  • Set a non-opaque url in testEnvironmentOptions.
  • Centralize a storage mock in a shared setup file.
  • Reset storage between tests to avoid cross-test leakage.

Frequently asked questions

What causes ""SecurityError: localStorage""?
With no configured URL, jsdom runs at about:blank, an opaque origin. Per the HTML storage spec, localStorage on an opaque origin must throw.
How do I fix "SecurityError: localStorage"?
Set a real URL so the origin is no longer opaque and storage works.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card