Fix - ReferenceError window is not defined in JavaScript


Borislav Hadzhiev

Tue Oct 19 20212 min read


Photo by pparnxoxo

Fix - ReferenceError window is not defined #

The "ReferenceError: window is not defined" error occurs for multiple reasons:

  1. Using window in Node.js.
  2. Using window on the server (e.g. server side rendering in Next.js).
  3. Misspelled the window global variable (should be all lowercase).

referenceerror window is not defined

The window represents a window containing a DOM document and is only available in the browser.

Node.js does not provide a browser environment, it's a server side runtime, so we can't use the window variable in Node.

If you are getting "ReferenceError: window is not defined" in the browser, try to move your JS script tag to the bottom of the body tag:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- Your HTML here --> <!-- 👇️ Script at bottom of body --> <script type="module" src="index.js"></script> </body> </html>

You might have some addons that are ran before the DOM is created.

The window global variable represents the window in which the script is running (browser side).

If you're using React.js or Next.js and you need to check if you're on the browser (can use window) or on the server (can't use window), you can do this in the following way:

if (typeof window !== 'undefined') { console.log('You are on the browser') // ✅ Can use window here } else { console.log('You are on the server') // ⛔️ Don't use window here }

We check if the global window variable does not have a type of undefined. If the window global is defined, we are on the browser and can use the window variable.

To solve the"ReferenceError: window is not defined" error, make sure to only use the window global variable on the browser. The variable represents a window containing a DOM document and can't be used on the server side (e.g. in Node.js).

If you need to define global variables in Node.js, you can define them using global, not window.

global.test = 'EXAMPLE';

And now we can use the variable in some other file:

import './index.js'; console.log(global.test); // 👉️ "EXAMPLE"

But it's much better to simply export a variable from the index.js file and import it as needed.

export const test = 'example';

Now we can import the variable in another file.

import {test} from './index.js'; console.log(test); // 👉️ "example"

This is a much better and more explicit approach than defining global variables.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.