Solving the ‘Window is Not Defined’ Error in Next.js

Updated: January 10, 2023 By: Goodman Post a comment

This article shows you a few solutions to fix the window is not defined error in Next.js.

Understanding The Problem

When working with Next.js, you are likely to run into the window is not defined error at least one time in your career. The error occurs when you attempt to access the window object on the server side while the window object is only available in the browser environment. This error can also happen when you use a functionality or component (that needs the window object) provided by a third-party library.

The code below is an illustration of causing the error:

// pages/index.js
export default function Home() {
  console.log(window.innerWidth);
  console.log(window.innerHeight);

  return (
    <div style={{ padding: 30 }}>
      <h1>Sling Academy</h1>
    </div>
  );
}

Screenshot:

Solutions

Checking the existence of the window object

To avoid the window is not defined error, you should always remember to check for the existence of the window object before using it. This will ensure that your app will not crash if it is running in a non-browser environment:

// pages/index.js
export default function Home() {
  if (typeof window !== 'undefined') {
    console.log(window.innerWidth);
    console.log(window.innerHeight);
  }

  return (
    <div style={{ padding: 30 }}>
      <h1>Sling Academy</h1>
    </div>
  );
}

Using the useEffect hook

The useEffect hook will always run in the browser, so you can use this to ensure that your code is only executed on the client, like this:

// pages/index.js
import { useEffect } from 'react';
export default function Home() {
  useEffect(() => {
    console.log(window.innerWidth);
    console.log(window.innerHeight);
  }, []);

  return (
    <div style={{ padding: 30 }}>
      <h1>Sling Academy</h1>
    </div>
  );
}

Cheer!