[Solved] Window is not defined in Next.js React app

Article Tarif Hossain

Today we would like to talk about the most common error that NextJS programmers come across: window is not defined. If we have worked with NextJS for a day, or for a year, chances are we have seen this error. It might seem silly, but we have seen experienced programmers confused by this error.

If we write code like this in your NextJS app, it will fail with the error window is not defined.

const width = window.innerWidth;

But why is window undefined?

NextJS is a framework that allows you to build Static and Server Side Rendered Apps. It uses NodeJS to render your application and window is not defined in NodeJS. That means that we need to be careful that our code that accesses the window object is not run in NodeJS.

Solution: Use the useEffect hook

We only access the window object when we are inside of a useEffect hook. This ensures that our code only runs on the client-side. The following example shows an image component that is the same width as the viewport. To do this, we use a combination of useState and useEffect to safely get and store the window.innerWidth.

import React from "react";

const Image = (props) => {
  const [width, setWidth] = React.useState(0);
  React.useEffect(() => {
    setWidth(window.innerWidth);
  });
  return <img src={props.src} style={{ width: width }} />;
};


That’s all for now! We hope this has cleared up some confusion about the most common NextJS error out there. Let us know in the contact section if you have experienced this error in your applications!