DEV Community

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

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