isotropic-2022
Share
Blog
Search
Menu

How To Solve ReferenceError window is not defined in JavaScript

By Greg Murray
|
Last updated on April 8th, 2022
|

JavaScript is a programming language with the sole purpose of allowing developers to add interactivity to web pages. At least, that was its sole purpose. Until Node.js came out. That brought JavaScript out from under the hood of the client and into the world of servers and other non-browser based programming applications.

Since its original purpose was to provide functionality for client-side development, JavaScript was built with many useful features that are only useful when working within a browser. Now that JavaScript is used just about everywhere, some care needs to be taken to ensure that you are not trying to do something browser specific while not in a browser environment.

The Problem

It is not uncommon to want or need to access the window global object from your JavaScript code. For example, you may be trying to access a web page’s innerWidth or innerHeight from the window object. Whatever the case may be, in some situations you might find yourself confronted by a message in your console: ReferenceError: window is not defined

undefined_window_error

There could be a few different reasons why this is happening, but the cause is all the same: you are attempting to access window from a Node.js environment. This is a common error if you are:

  1. Simply looking for a global variable to use in your Node.js app
  2. Building an app that uses server-side rendering (SSR) or static site generation (SSG) with frameworks such as Gatsby.js, Nuxt.js, or Next.js. You may think that you are writing frontend code so the window object is available but the code is actually being run on the server first which causes the error, typically at build time.
💡

SSR and SSG frameworks typically go through a pre-render step when they build your app. This important step renders as much HTML as possible and runs much of your JavaScript code on the server in order to improve performance. The process of picking up where this step left off on the frontend is called hydration and is supported in both Vue and React.

The Solution

Fixing a window is not defined error can be quite simple. In most cases, all you will need to do is wrap your window associated code in logic to make sure it is only used on the client. For example, let’s say you want to get a page’s width and height:

let width = 0, height = 0; width = window.innerWidth; height = window.innerHeight;

Wrap this code in a check to see make sure window is defined and that error will no longer be a problem.

if (typeof window !== "undefined") { width = window.innerWidth; height = window.innerHeight; } console.log(width); // 0 if on the server, window width if on the client console.log(height); // 0 if on the server, window height if on the client

If you are specifically working on a Node.js application and still receive this error, it is because the window object does not actually exist in a Node.js environment. To resolve this, all you would need to do is swap out your usage of window with the globalThis object. This object essentially performs the same role in Node.js that window plays while working directly with a web page: it gives you access to a global variable (among other things of course).

window.foo = "bar"; // replace this globalThis.foo = "bar"; // with this

It’s worth mentioning that you could also reevaluate if you truly need a global object like globalThis or window in your Node.js application. You could avoid the problem altogether by defining your variable in one module and importing it wherever you need it.

// foo.js const foo = "bar"; module.exports = { foo, }; // needsFoo.js const { foo } = require("./foo"); console.log(foo); // 'bar'

Or, if you prefer the ES6+ method:

// ES6+ // foo.js export const foo = "bar"; // needsFoo.js import { foo } from "./foo.js"; console.log(foo); // 'bar'

Between both solutions you should now be enjoying a programming experience without any window is not defined errors. If a new error comes up feel free to check out our archive for a solution or leave a comment if we haven’t covered it yet. Thanks for reading!

The Isotropic Codex is a collection of code snippets and education for WordPress, web and WooCommerce developers.
Subscribe & Share
If you liked this content, subscribe for our monthly roundup of WordPress news, website inspiration, exclusive deals and interesting articles.
Unsubscribe at any time. We do not spam and will never sell or share your email.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Article By
Greg Murray
Contributors/Editors
notloggedin
I’m a passionate and driven web developer with an eye for design and appreciation for the human aspect of technology. I am experienced with building websites for small to medium businesses or large web applications for big businesses. Websites can be custom made using cutting edge technology and responsive design or created using the website builder of your choice.
We're looking for new authors. Explore Isotropic Jobs.
Close
🇺🇸 English
Save posts, access exclusive content, join members-only communities and more.
Dark Mode Toggle
Love web dev? Join the Isotropic weekly newsletter.
cross
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram
0

Your Cart is Empty