Home·Error messages

node · JavaScript

The message

ReferenceError: window is not defined

What it means

The code ran inside Node on the server rather than in a browser. Node has no window, no document and no localStorage, so touching window while a module is being loaded in a framework that server-renders first, such as Next.js or Nuxt, stops here — often it is a single line outside the component, or the import of a browser-only library itself. If the work is browser-only, guard it with typeof window !== 'undefined', or better, move it inside useEffect, which only ever runs in the browser. When a whole library is browser-only, Next.js can exclude it from the server render with dynamic(() => import('./C'), { ssr: false }) — at the cost of that part being absent from the server-rendered HTML.

The fix

There is no one-line command for this. The explanation says what to look at instead.

Printed by
node
JavaScript
15

Browser and Node errors usually tell you what broke and not why the value became what it was — you read undefined, it was not a function, it was not JSON — so the place to fix is upstream of the line that threw, and silencing just that line with ?. and default values makes the same problem reappear further away in a form that is harder to recognise.

Reading an error message

  • Read from the first line down. The lower you go the more it is about the tool’s internals; the cause is usually at the top.
  • If there is a file and a line number, start there — not the top stack frame, but the topmost line that names a file you wrote.
  • Search the message verbatim, but strip your own paths and variable names first; those are what stop the search from matching.
  • The same condition is worded differently across tool versions. If results look wrong, add the version number to the query.
  • Before pasting a fix, check what it throws away. Some of these cannot be undone.

Common questions

Q. What does “ReferenceError: window is not defined” mean?

The code ran inside Node on the server rather than in a browser. Node has no window, no document and no localStorage, so touching window while a module is being loaded in a framework that server-renders first, such as Next.js or Nuxt, stops here — often it is a single line outside the component, or the import of a browser-only library itself. If the work is browser-only, guard it with typeof window !== 'undefined', or better, move it inside useEffect, which only ever runs in the browser. When a whole library is browser-only, Next.js can exclude it from the server render with dynamic(() => import('./C'), { ssr: false }) — at the cost of that part being absent from the server-rendered HTML.

Q. How do I fix it?

There is no one-line command. The explanation above says what to look at instead.

Q. Which tool prints this?

node. It sits under JavaScript, and the message runs to 5 words.

Errors nearby