DEV Community

Discussion on: How to solve "window is not defined" errors in React and Next.js

Collapse
 
rowin1125 profile image
Rowin Mol • Edited

Niceee!

If you don't want to have a lot of boilerplate code, you could simple write:

const isBrowser = window && window.addEventListener(.......blabla)
Enter fullscreen mode Exit fullscreen mode

and use this variable as a conditional.

Also if you use the first option, please remember to unsubscribe your eventListener in the useEffect or you gonna have a bad time 😭 .

useEffect(function onFirstMount() {
    function onScroll() {
      console.log("scroll!");
    }

    window.addEventListener("scroll", onScroll);

   return () => {
      window.removeEventListener("scroll");
    }
  }, []);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
clxrityy profile image
clxrity

I found this only works (2024) when adding window to the dependency array.

Collapse
 
vvo profile image
Vincent Voyer • Edited

Hey there Rowin, you might have a different setup but const isBrowser = window won't work at least in Next.js pre-rendering. You'll get the same error (just tried it again). I think anytime such code would go through Node.js it would fail, as shown in a REPL:

> node
Welcome to Node.js v12.18.0.
Type ".help" for more information.
> window && "ok"
Uncaught ReferenceError: window is not defined
Enter fullscreen mode Exit fullscreen mode

As for unsubscribing the listener, this is already done in the code samples from the article so maybe you missed that or there's some other place I forgot to do it?

Thanks

Collapse
 
teamroggers profile image
Rogier Nitschelm

Perhaps like this?

const isBrowser = () => typeof window !== "undefined"

// node
isBrowser() // false

// browser
isBrowser() // true
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
vvo profile image
Vincent Voyer

Yes that would work indeed! Thanks :)

Thread Thread
 
vvo profile image
Vincent Voyer

Just added a new solution and thank you note :)

Thread Thread
 
ariyou2000 profile image
ARiyou Jahan

In a tread related to this problem in Next.JS official GitHub issue page mentioned that it is wrong to do so and you need to explicitly check typeof window !== "undefined" wherever you need it:
NextJS GitHub issues page

Consider reading my solution as well. it's inspirred by this post. So thank you Vincent for idea.
NextJS - Access window and localStorage