Fix - ReferenceError window is not defined in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

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:

index.html
<!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:

index.js
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.

index.js
global.test = 'EXAMPLE';

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

another-file.js
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.

index.js
export const test = 'example';

Now we can import the variable in another file.

index.js
import {test} from './index.js'; console.log(test); // ๐Ÿ‘‰๏ธ "example"

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

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee