AI Workshop: learn to build apps with AI →
Debugging: referenceerror: window is not defined, how to solve

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


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.

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 detail in my DOM (Document Object Model) guide.

With Node.js in particular there’s no way to work around the problem—you must find where window is used and revisit the code to figure out why you’re accessing it.

You are running frontend code in a backend environment.

In Next.js you can fix this problem by wrapping the code you run in a conditional.

The code might run in both environments: on the frontend when you navigate to a page, and on the server if you use server-side rendering (for example with getServerSideProps()).

In that case, wrap the code in a conditional that checks if window is available:

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.

Lessons in this unit:

0: Introduction
1: Fix Node.js imports types errors in VS Code
2: ▶︎ referenceerror: window is not defined, how to solve
3: Use the Chrome DevTools to debug a Node.js app
4: Error handling in Node.js
5: How to solve the `util.pump is not a function` error in Node.js