DEV Community

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

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