referenceerror: window is not defined, how to solve
Find out how to fix the error referenceerror: window is not defined
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 is details in my extensive DOM Document Object Model guide.
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.
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 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.
download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.