Search code examples
node.jsreactjswebpackwebpack-dev-server

Error `window not defined` in Node.js


I know window doesn't exist in Node.js, but I'm using React and the same code on both client and server. Any method I use to check if window exists nets me:

Uncaught ReferenceError: window is not defined

How do I get around the fact that I can't do window && window.scroll(0, 0)?


Solution

  • Sawtaytoes has got it. I would run whatever code you have in componentDidMount() and surround it with:

    if (typeof window !== 'undefined') {
      // code here
    }
    

    If the window object is still not being created by the time React renders the component, you can always run your code a fraction of a second after the component renders (and the window object has definitely been created by then) so the user can't tell the difference.

    if (typeof window !== 'undefined') {
        var timer = setTimeout(function() {
            // code here
        }, 200);
    }
    

    I would advise against putting state in the setTimeout.