Error `window not defined` in Node.js

Kevin Ghadyani picture Kevin Ghadyani · Feb 13, 2016 · Viewed 22.9k times · Source

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)?

Answer

Jeff Diederiks picture Jeff Diederiks · Feb 13, 2016

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.