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
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?
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
Niceee!
If you don't want to have a lot of boilerplate code, you could simple write:
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 😭 .
Hey there Rowin, you might have a different setup but
const isBrowser = windowwon'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: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
Perhaps like this?
Yes that would work indeed! Thanks :)
Just added a new solution and thank you note :)
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
I found this only works (2024) when adding
windowto the dependency array.