Error `window not defined` in Node.js

This will settle that issue for you:

typeof(window) === 'undefined'

Even if a variable isn't defined, you can use typeof() to check for it.


This kind of code shouldn't even be running on the server, it should be inside some componentDidMount (see doc) hook, which is only invoke client side. This is because it doesn't make sense to scroll the window server side.

However, if you have to reference to window in a part of your code that really runs both client and server, use global instead (which represents the global scope - e.g. window on the client).


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.