Handling “window is not defined” Error in React and Next js for Client-Side Code

Saileshadhikari
2 min readJul 25, 2023

In React and Next js it’s common to encounter the error “window is not defined.” This error occurs when attempting to access the window object, which represents the browser environment, in a context where it is not available, such as during server-side rendering or in Node.js.

In this article, we will explore how to address this error in React by using conditional rendering techniques to ensure client-side code executes only when the window object is defined.

Screenshot of “window is not defined error”

To handle the “window is not defined” error in React & Next js, we can use the conditional rendering technique. Conditional rendering allows us to render specific components or execute code based on conditions. In our case, we will check whether the window object is defined before rendering any client-side code.

Implement Conditional Rendering

Wrap the code that relies on the window object inside a conditional check. We’ll use the (typeof window !== ‘undefined’) condition to ensure that the code is executed only in a browser environment.

if(typeof window !== 'undefined')
{
// Your client-side code that uses window goes here
}

Conclusion

By implementing the conditional rendering approach using (typeof window !== ‘undefined’), we can safely handle the “window is not defined” error in React & Next js . This technique allows us to execute client-side code only when running in a browser environment, preventing any issues during server-side rendering.

--

--

Saileshadhikari

Frontend developer || software engineer || Technical writer