[Bug]: localStorage.getItem is not a function on Node.js 25+ (window = globalThis breaks SSR guard)

Author: 0s1nCreated Apr 18, 2026Updated Apr 23, 2026

What happened?

On Node.js 25+, the SSR guard used throughout next-themes breaks silently:

```js // next-themes evaluates this ONCE at module load time const J = typeof window == "undefined" ```

Node.js 25 ships an experimental implementation of the Web Storage API where `window` is defined as an alias for `globalThis`. This means:

  • `typeof window` → `"object"` (not `"undefined"`) on the server
  • `J = false` at module load time
  • `next-themes` then calls `localStorage.getItem(storageKey)` thinking it's in the browser
  • Node.js 25's partial `localStorage` implementation does not implement `getItem` correctly
  • Result: `TypeError: localStorage.getItem is not a function` on server startup

Error message

``` TypeError: localStorage.getItem is not a function at Z (next-themes/dist/index.js) at useState initializer ```

Version

  • next-themes: 0.4.6 (latest)
  • next: 15.3.1
  • node: v25.8.2
  • react: 19.1.0

How to reproduce

  1. Install Node.js 25+
  2. Create a Next.js 15 app with next-themes
  3. Wrap layout in <ThemeProvider>
  4. Run next dev or next build

Root cause

The `typeof window == "undefined"` pattern has been the universal SSR detection idiom for years. Node.js 25 breaks this assumption by aliasing `window` to `globalThis`, which is defined in all environments.

The fix should use `typeof globalThis.document` or `typeof globalThis.localStorage` as guards instead of `typeof window`, since `document` and a complete `localStorage` remain browser-only APIs.

Workaround (until fixed)

Patch `globalThis.localStorage` before any module loads using Next.js instrumentation:

```ts // instrumentation.ts export async function register() { if (typeof globalThis.localStorage !== "undefined") { const store: Record<string, string> = {} Object.defineProperty(globalThis, "localStorage", { configurable: true, writable: true, value: { getItem: (key: string) => store[key] ?? null, setItem: (key: string, value: string) => { store[key] = value }, removeItem: (key: string) => { delete store[key] }, clear: () => { Object.keys(store).forEach(k => delete store[k]) }, key: (index: number) => Object.keys(store)[index] ?? null, get length() { return Object.keys(store).length }, }, }) } } ```

Before submitting

  • I've made research efforts and searched the documentation
  • I've searched for existing issues