Referenceerror: window is not defined

One of the errors you may encounter is the “ReferenceError: window is not defined” message, which indicates that the “window” object is not accessible or available in the current context.

ReferenceError is a common error in JavaScript that occurs when a variable or object is referenced but not defined.

In this article, we will explore the causes behind this error and discuss effective solutions to resolve it.

Why Referenceerror: window is not defined occur?

The error “ReferenceError: window is not defined” can occur in JavaScript for various reasons such as:

  • Using the window object in Node.js
  • Using the window object on the server
  • Misspelling the window global variable

How to fix Referenceerror: window is not defined?

Here are the following ways you can try to fix the Referenceerror: window is not defined.

1. Use typeof

The first solution suggests using the “typeof” operator to tackle a specific issue.

Instead of comparing a non-existent variable called “window” to “undefined,” which would result in an error, you can use “typeof window !== ‘undefined'”.

This approach allows you to check the type of “window” without trying to evaluate it. In the case of Node.js, it will return “undefined.”

2. Use React useEffect

Another solution, specifically for React, involves using a special function called “useEffect.”

By utilizing this function, you can ensure that certain code only runs during the rendering phase and not on the server.

To implement this in a component called “Scroll,” you would update the code as follows:

javascriptCopy codeimport React, { useEffect } from "react";

export default function Scroll() {
  useEffect(function mount() {
    function onScroll() {
      console.log("scroll!");
    }

    window.addEventListener("scroll", onScroll);

    return function unMount() {
      window.removeEventListener("scroll", onScroll);
    };
  });

  return null;
}

To include this updated component in your React app, you would make the following changes to the “index.js” file:

javascriptCopy codeimport Scroll from "../components/Scroll";

export default function Home() {
  return (
    <div style={{ minHeight: "1000px" }}>
      <h1>Home</h1>
      <Scroll />
    </div>
  );
}

3. Dynamic Loading

The third solution involves a technique called dynamic loading. It allows you to load the “Scroll” component using dynamic imports and a special option called “ssr: false.”

This ensures that the component is not rendered on the server-side at all.

This approach is particularly useful when you’re importing external modules that rely on the “window” object.

Here’s how you would modify the code for the “Scroll” component:

function onScroll() {
  console.log("scroll!");
}

window.addEventListener("scroll", onScroll);

export default function Scroll() {
  return null;
}

And in the “index.js” file, you would make the following adjustments:

import dynamic from "next/dynamic";

const Scroll = dynamic(
  () => {
    return import("../components/Scroll");
  },
  { ssr: false }
);

export default function Home() {
  return (
    <div style={{ minHeight: "1000px" }}>
      <h1>Home</h1>
      <Scroll />
    </div>
  );
}

If you don’t require the functionality provided by the “useEffect” function, you can simply remove it from the code.

Alternatively, if your goal is to load the “Scroll” component globally without having it mount or unmount on page changes, you can load it only in the “_app.js” file.

Alternative solutions:

Here are other solutions you can consider in resolving the error.

Put the JS script tag at the bottom of body tag

When you raise the error in the browser, alternatively place the Js script tag at the bottom of the body tag.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <!-- Your HTML here -->

    <!-- 📌 Script at bottom of body -->
    <script type="module" src="index.js"></script>
  </body>
</html>

Anyway, here are other fixed errors you can refer to when you might encounter them.

Conclusion

In conclusion, to resolve the “ReferenceError: window is not defined” error in JavaScript:

  • Avoid using the window object in Node.js or on the server.
  • Check if the window object is defined before using it in a browser context.
  • Place your script tag at the bottom of the body tag in HTML files.
  • Ensure that you have correctly spelled the window object as “window” with a lowercase “w.”

We hope this guide has assisted you in resolving the error effectively.

Until next time! 😊

Leave a Comment