How to fix ReferenceError window is not defined

You’ll encounter the “ReferenceError: window is not defined” error when you try to access the window object in an environment where it’s not available.

The window object is a built-in object in JavaScript that represents the browser window. It provides properties and methods for manipulating the browser window, like its size, location, and accessing the DOM.

This error typically happens in two common scenarios:

  • Server-side Rendering (SSR): Frameworks like Next.js allow you to pre-render your web pages on the server for SEO and performance benefits. However, the window object isn’t available on the server-side because it’s a browser concept. If your code tries to access window during this pre-rendering stage, you’ll run into this error.

  • Node.js Environment: JavaScript can also run outside the browser in environments like Node.js. Since Node.js isn’t a browser, it doesn’t have a window object, and trying to access it there will cause this error.

Here are some ways to address this error:

Check for window before use

You can add a conditional check to see if window is defined before using it. This ensures your code only executes the parts that rely on the window object when it’s actually available in a browser.

This approach leverages the typeof operator to determine the data type of the window object. Since the window object is absent in environments like Node.js, it will evaluate to “undefined”. Here’s how you can use it:

if (typeof window !== 'undefined') {
  // Your code that uses the window object
  console.log(window.location.href); // Example: access window property
} else {
  // Code to handle the case where window is not available (optional)
  console.log("window object not defined (likely Node.js environment)");

Use useEffect in React

If you’re using React, the useEffect hook lets you run code after a component mounts. This is a good place to put code that interacts with the window object because it guarantees the component is in the browser and window is defined.

import React, { useEffect, useState } from 'react';

function MyComponent() {
  const [innerWidth, setInnerWidth] = useState(0);

  useEffect(() => {
    // This function will be called after the component mounts
    const handleResize = () => {

    // Add event listener to window resize event
    window.addEventListener('resize', handleResize);

    // Cleanup function: removes event listener on unmount
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return (
      Window inner width: {innerWidth}

export default MyComponent;