referenceerror: window is not defined, how to solve

By

Learn how to fix the referenceerror: window is not defined error in Node.js or Next.js by guarding browser-only code with a typeof window check first.

~~~

Here’s how to fix the “referenceerror: window is not defined” error that you might have in Node.js or with a tool like Next.js: find the code that uses window, and make sure it only runs in the browser.

Why does this error happen?

window is an object that’s made available by the browser, and it’s not available in a server-side JavaScript environment.

I describe the window object in details in my extensive DOM Document Object Model guide.

You are running frontend code in a backend environment.

The usual triggers: accessing window, document or localStorage at the top level of a file, or importing a library that does so as soon as it loads.

With Node.js in particular there’s no way to workaround the problem - you must find the particular place where window is used, and revisit the code to figure out why you are accessing the window object.

How to fix it in Next.js

In Next.js this error is common because the same code runs in two places.

The code might be running in both situations - frontend, when you navigate to a page using a link, and server-side if you require server-side into your page, for example by running getServerSideProps().

In this case, you can limit the reference into a conditional that checks if the window object is available, like this:

if (typeof window !== 'undefined') {
  //here `window` is available
}

And this will fix your problem, since you only run anything inside the conditional in a browser environment.

Alternatively, you can move the browser-only code inside a useEffect() hook:

useEffect(() => {
  console.log(window.innerWidth)
}, [])

Effects only run in the browser, after the component is mounted, so window is guaranteed to exist inside them.

Be careful how you write the check

The typeof part is not optional. This version does not work:

if (window !== undefined) {
  //...
}

That line throws the exact same “window is not defined” error, because reading a variable that was never declared is itself a ReferenceError.

typeof is the one operator that’s safe to use on names that don’t exist. Instead of throwing, it returns the string 'undefined'. That’s why the fix always starts with typeof window.

Tagged: Node.js · All topics
~~~

Related posts about node: