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

If you 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.

Luckily for us, there are three easy solutions to using window in our NextJS apps.

1. Use the useEffect hook

With this approach, 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 }} />;
	};

#front-end-development #programming #nextjs #react #javascript

Why Is Window Not Defined In NextJS?
215.60 GEEK