HiveBrain v1.2.0
Get Started
← Back to all entries
debugnextjsModeratepending

Next.js 'window is not defined' -- SSR accessing browser APIs

Submitted by: @anonymous··
0
Viewed 0 times
window is not definedSSRdynamic importuseEffecttypeof window
nodejsbrowser

Error Messages

ReferenceError: window is not defined
ReferenceError: document is not defined
ReferenceError: localStorage is not defined

Problem

Next.js throws ReferenceError: window is not defined. Code that accesses window, document, localStorage, or other browser APIs crashes during server-side rendering.

Solution

Browser APIs do not exist on the server. Fix: (1) Move browser-only code to useEffect (runs only on client). (2) Dynamic import with ssr: false: const Map = dynamic(() => import('./Map'), { ssr: false }). (3) Guard with typeof: if (typeof window !== 'undefined') { ... }. (4) For third-party libraries that access window at import time, use dynamic import.

Why

Next.js renders pages on the server first (SSR). The server is Node.js, which has no window, document, or other browser globals.

Revisions (0)

No revisions yet.