How to avoid errors using window on React.js SSR

Author post avatar

Dante Calderón | July 31, 2022

How to avoid errors using window on React.js SSR cover

Sometimes when you are developing your React components on SSR frameworks like Gatsby or Next.js, you run into this error:

ReferenceError: window is not defined

This is a typical error when you try to use the window global variable on the server, that is because window only exists on the browser, not on the server. And in the compilation time, we get that error.


Fortunately, there is a useful library that helps us solve this issue easily, it’s called browser-monads-ts, you only need to install it and import and use it in your component like this:

// Import window from the browser-monads-ts library
import { window } from 'browser-monads-ts';

export function MyComponent() {
	useEffect(() => {
		// You can use window anywhere in your code
	}, []);

	return <div>Hello</div>

What this library does is when it is on the client it will return the real value of window otherwise it will return a non-functional value preventing you from getting a reference error.

TAGS: ⚛️ ReactJs🤔 How To
Author post avatar

Written by

Dante Calderón

Hi, I'm Dante Calderón, web developer. Click here if you want know more about me or checkout my portafolio.