Undefined ‘window’ in Gatsby using Hooks

Surajudeen Akande
2 min readJan 6, 2021

--

The error.

Having the error ‘window is not defined’ in Gatsby is not a big deal, but it might jolt newbies especially when wrapping your head around Server-side Rendering.

You might not encounter this error on development, but when you try to build your Gatsby app for production, this error can pop up on your face.

This has been solved before, and the commonest way you can find it on the internet is either through the debugging HTML builds on the Gatsby documentation or simply calling the window object on ComponentDidMount lifecycle.

The problem is clear by now, the window object wants to build on your server but it not available there so you need your window to be available in your client before calling it, simple.

Sometimes, your codebase might be employing hooks instead of a lifecycle method, so this blog is all about that.

This blog assumes you already know your way around Gatsby.

For example, I have a feature in my gatsby app that requires the current base URL and query parameters. In the src/hooks directory, I will create a file called getUrlParameter.js.

By this, the window object and some of the properties are now available and you can pass them to your components like:

In case you want to read further regarding hooks, I found this post very useful.

That is all 👌.

--

--

Surajudeen Akande
Surajudeen Akande

Written by Surajudeen Akande

Apprentice, T-shaped, Goal-digger and Public Speaker

No responses yet