DEV Community

Jishnu-02
Jishnu-02

Posted on

Window not defined

Server Error
ReferenceError: window is not defined

Can't surpass this error...

code:https://gist.github.com/Jishnu-02/b90cab1c887ac8b64122ffbb29844313

Top comments (6)

Collapse
 
sfiquet profile image
Sylvie Fiquet

I don't get what your point is, are you asking for help?

It's normal to get an error, window is not defined on the server. Remember that Next runs your code on the server when building the HTML file.

Initialise your state to 0 and update it to window.innerWidth in useEffect.

Collapse
 
jishnu02 profile image
Jishnu-02

can u show me how to do it?

Collapse
 
sfiquet profile image
Sylvie Fiquet

Something like that:

const [windowWidth, setWindowWidth] = useState(0)

// runs only once, on mount
useEffect(() => {
  if (window !== undefined){
    setWindowWidth(window.innerWidth)
    window.addEventListener('resize', handleWindowWidth)
  }
}, [])
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
jishnu02 profile image
Jishnu-02

Thank You.

Collapse
 
majklzumberi profile image
majkl zumberi

You are using next.js so you can use Window only client side, which means you can use It only on useEffect hook.

Window Is not defined on serverside

Collapse
 
jishnu02 profile image
Jishnu-02

can u show me how to do it?