April 25, 2020 by Kostas Vrouvas

How to fix the window is not defined in Gatsby, and other static generators

When you reference “browser globals” like window or document, you might notice that in gatsby develop works as expected, but fails to do so in gatsby build. If this is your problem you should see an error like “window is not defined”.

Why is this happening

During development, Gatsby will run the code in the browser where window is available. During build though, Gatsby compiles your code on the Server Side, and hence window is not accessible.

How to fix this

In order to fix this, you can check before calling the code if window is defined so the code doesn’t run while Gatsby is building or, use React’s componentDidMount().

componentDidMount()is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

Use it like this:

componentDidMount() {
//Your window here

And that’s it!

© 2020 Kostas Vrouvas, Built with Gatsby