|

|  ReferenceError: window is not defined in Next.js: Causes and How to Fix

ReferenceError: window is not defined in Next.js: Causes and How to Fix

February 10, 2025

Discover the reasons behind "ReferenceError: window is not defined" in Next.js and learn solutions to fix this common error in your applications.

What is ReferenceError: window is not defined in Next.js

 

Understanding ReferenceError: window is not defined in Next.js

 

In Next.js, a framework based on React, you may encounter the ReferenceError: window is not defined when trying to use some properties or methods that are unique to web browsers. Unlike client-side JavaScript, Node.js, which runs on the server-side, lacks access to browser-specific APIs like the window object.

 

  • Server-Side Rendering (SSR): Next.js utilizes Server-Side Rendering, executing JavaScript on the server before sending HTML to the client. During this render cycle, objects inherent to the browser environment, like `window`, are unavailable.
  •  

  • Code Execution Context: When you attempt to access the `window` object either in component lifecycle methods or hooks like `useEffect` without checking the environment, you can face a `ReferenceError`. This is because the code may run on the server where `window` does not exist.
  •  

  • JavaScript Runtime Differences: The discrepancy between the server-side Node.js runtime and the client-side browser environment is pivotal. Browser-specific API calls lead to these errors due to the absence of objects like `window`, `document`, and `navigator` that are present in browsers but not on the server.
  •  

 

Recognizing When and Why It Happens

 

  • Attempting to access properties like `window.location`, `window.localStorage`, or starting timers with `window.setTimeout` directly within the top-level of your module or outside of lifecycle methods/hooks.
  •  

  • Using third-party libraries that depend on the `window` object without server-side compatibility could introduce this error when rendering pages with Next.js.
  •  

 

Example Scenario

 

Consider the following example where the window object is accessed directly in a Next.js component:

 

const MyComponent = () => {
  const [width, setWidth] = React.useState(window.innerWidth);

  return (
    <div>
      <p>Current window width: {width}px</p>
    </div>
  );
};

export default MyComponent;

This code will work flawlessly in pure client-side rendering but will result in a ReferenceError: window is not defined in Next.js since window.innerWidth is evaluated during server-side rendering.

 

Remember that understanding the separation of server and client-side contexts in Next.js is crucial to effectively managing errors like ReferenceError: window is not defined. This error fundamentally arises from attempting to manipulate or reference browser-specific objects like window during the server-side rendering phase, where such objects do not exist.

What Causes ReferenceError: window is not defined in Next.js

 

Causes of ReferenceError: window is not defined in Next.js

 

  • Server-side Rendering (SSR): Next.js enables both server-side rendering and static site generation. During rendering on the server, the absence of browser-specific objects like window triggers this error, as these objects are part of the client-side environment.
  •  

  • Next.js Initial Data Fetching: When using methods like getServerSideProps or getStaticProps, the code runs on the server. Accessing the window object within these methods will lead to a ReferenceError since the server has no knowledge of the browser's environment.
  •  

  • Use of JavaScript Libraries or Components with Browser-Specific Code: Libraries or components that access window without considering the environment can cause the error when rendering on the server. For instance, a third-party plugin might call window.localStorage, assuming it's always executed in a client-side context.
  •  

  • Lifecycle Methods in React Components: If you have any code referring to window within the component's lifecycle methods like componentDidMount or useEffect, it could produce an error during SSR. This happens when code within these methods is mistakenly executed on the server.
  •  

  • Next.js Dynamic Imports with SSR Enabled: When dynamic imports are used in Next.js without proper conditional checks for the presence of window, the server-side execution causes a ReferenceError. This is especially problematic when dynamically importing browser-heavy libraries.

 

Omi Necklace

The #1 Open Source AI necklace: Experiment with how you capture and manage conversations.

Build and test with your own Omi Dev Kit 2.

How to Fix ReferenceError: window is not defined in Next.js

 

Use Dynamic Imports

 

  • To handle server-side rendering in Next.js where the traditional browser API is used, leverage dynamic imports. Dynamic imports help in loading a component or library only on the client side. Using next/dynamic, you can ensure that parts of your code only run in the browser environment.
  •  

  • Here's an example of using Next.js dynamic imports:

 

import dynamic from 'next/dynamic';

const MyComponent = dynamic(() => import('../components/MyComponent'), { ssr: false });

export default function Home() {
  return <MyComponent />;
}

 

Check the Execution Environment

 

  • Since `window` is only available in the browser, you can use conditional checks to execute specific code that relies on `window` or other browser-specific objects only in a client-side environment.
  •  

  • Here's an example:

 

if (typeof window !== 'undefined') {
  // Client-side only code
  console.log('Client-side: ', window.location.href);
}

 

React useEffect Hook

 

  • The useEffect Hook can be utilized to perform operations only once the component is mounted, ensuring that the code runs only on the client side. This is because useEffect is not executed during server-side rendering.
  •  

  • Example usage:

 

import { useEffect } from 'react';

export default function Home() {
  useEffect(() => {
    console.log('Window location: ', window.location.href);
  }, []);
  
  return <div>Check the console!</div>;
}

 

Custom Hook for Client-Side Code

 

  • Create a custom hook that executes a client-side operation, abstracting away repetitive checks and keeping code organized.
  •  

  • Example of a custom hook:

 

import { useEffect, useState } from 'react';

function useClientOnly(callback) {
  useEffect(() => {
    if (typeof window !== 'undefined') {
      callback();
    }
  }, []);
}

export default function Home() {
  useClientOnly(() => {
    console.log('Window location: ', window.location.href);
  });

  return <div>Running Client-Side Code!</div>;
}

 

Wrapping Components with HOC

 

  • Create a Higher-Order Component (HOC) to encapsulate client-specific logic and rendering, ensuring components are aware of their execution context.
  •  

  • Example of wrapping a component with an HOC:

 

import { useEffect } from 'react';

function withClientCheck(WrappedComponent) {
  return (props) => {
    useEffect(() => {
      if (typeof window !== 'undefined') {
        console.log('Running in Browser Environment');
      }
    }, []);
    
    return <WrappedComponent {...props} />;
  };
}

export default withClientCheck(HomeComponent);

 

Omi App

Fully Open-Source AI wearable app: build and use reminders, meeting summaries, task suggestions and more. All in one simple app.

Github →

Order Friend Dev Kit

Open-source AI wearable
Build using the power of recall

Order Now

Join the #1 open-source AI wearable community

Build faster and better with 3900+ community members on Omi Discord

Participate in hackathons to expand the Omi platform and win prizes

Participate in hackathons to expand the Omi platform and win prizes

Get cash bounties, free Omi devices and priority access by taking part in community activities

Join our Discord → 

OMI NECKLACE + OMI APP
First & only open-source AI wearable platform

a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded

OMI NECKLACE: DEV KIT
Order your Omi Dev Kit 2 now and create your use cases

Omi Dev Kit 2

Endless customization

OMI DEV KIT 2

$69.99

Speak, Transcribe, Summarize conversations with an omi AI necklace. It gives you action items, personalized feedback and becomes your second brain to discuss your thoughts and feelings. Available on iOS and Android.

  • Real-time conversation transcription and processing.
  • Action items, summaries and memories
  • Thousands of community apps to make use of your Omi Persona and conversations.

Learn more

Omi Dev Kit 2: build at a new level

Key Specs

OMI DEV KIT

OMI DEV KIT 2

Microphone

Yes

Yes

Battery

4 days (250mAH)

2 days (250mAH)

On-board memory (works without phone)

No

Yes

Speaker

No

Yes

Programmable button

No

Yes

Estimated Delivery 

-

1 week

What people say

“Helping with MEMORY,

COMMUNICATION

with business/life partner,

capturing IDEAS, and solving for

a hearing CHALLENGE."

Nathan Sudds

“I wish I had this device

last summer

to RECORD

A CONVERSATION."

Chris Y.

“Fixed my ADHD and

helped me stay

organized."

David Nigh

OMI NECKLACE: DEV KIT
Take your brain to the next level

LATEST NEWS
Follow and be first in the know

Latest news
FOLLOW AND BE FIRST IN THE KNOW

thought to action.

team@basedhardware.com

Company

Careers

Invest

Privacy

Events

Vision

Trust

Products

Omi

Omi Apps

Omi Dev Kit 2

omiGPT

Personas

Resources

Apps

Bounties

Affiliate

Docs

GitHub

Help Center

Feedback

Enterprise

© 2025 Based Hardware. All rights reserved.