|

|  Unhandled Rejection (ReferenceError): document is not defined in Next.js: Causes and How to Fix

Unhandled Rejection (ReferenceError): document is not defined in Next.js: Causes and How to Fix

February 10, 2025

Discover causes and solutions for the error "Unhandled Rejection (ReferenceError): document is not defined" in Next.js with this comprehensive guide.

What is Unhandled Rejection (ReferenceError): document is not defined in Next.js

 

Unhandled Rejection (ReferenceError): document is not defined in Next.js

 

In Next.js, an Unhandled Rejection error arising from a "ReferenceError: document is not defined" typically occurs when server-side code performs an operation that relies on the document object. Next.js uses both client-side and server-side rendering, and the document object is only available in the client's browser environment. This can become an issue because some code intended for client-side execution inadvertently runs during the server-side rendering (SSR) process where document is not available.

 

Understanding Server-Side Rendering (SSR) in Next.js

 

  • SSR in Next.js pre-renders pages on the server, allowing for a faster initial page load and better SEO performance. However, this environment does not include browser-specific APIs, like `document`, `window`, or `localStorage`.
  •  

  • When developing with Next.js, it’s crucial to ensure that any code using these APIs is only executed on the client-side. This means checking that the code is not run during the server-side rendering phase.

 

Common Scenarios Leading to "document is not defined"

 

  • **Component Lifecycle Methods:** Using method hooks such as `componentDidMount` or the `useEffect` hook improperly can cause issues if they include the `document` API directly in their logic, without checks for the execution environment.
  •  

  • **Third-Party Libraries:** Libraries or components that are not SSR compatible, which automatically use the `document` object, might throw this error when Next.js tries to render them on the server side.

 

Example Problematic Code

 

This error can be illustrated with a simple code snippet where server-side attempts to access document directly:

export default function MyComponent() {
  // This will fail during server-side rendering
  const element = document.getElementById('my-element');

  return <div id="my-element">Hello World</div>;
}

 

Conclusion

 

Handling this error effectively involves understanding the rendering cycles in Next.js and distinguishing client-only logic from universal logic appropriate for both server and client environments. This ensures that any references to browser-specific objects are managed and applied safely, guaranteeing that your Next.js application runs smoothly without encountering runtime errors or unhandled rejections during server-side rendering.

What Causes Unhandled Rejection (ReferenceError): document is not defined in Next.js

 

Understanding "document is not defined" in Next.js

 

In Next.js, encountering the error "Unhandled Rejection (ReferenceError): document is not defined" is common, particularly when working with server-side rendering (SSR). This error occurs due to differences between client-side and server-side environments.

 

  • Server-Side Rendering Context: Next.js is built with server-side rendering capabilities. When functions that access global variables specific to the browser, such as `document`, are executed during SSR, the server environment lacks these browser-specific objects, leading to the "document is not defined" error.
  •  

  • Executing JavaScript in Node.js: Next.js allows JavaScript code to be executed within a Node.js context during SSR. Since `document` is a global object provided by the browser, trying to access it while rendering on the server, which uses Node.js, can cause errors because Node.js does not provide or define the `document` object.
  •  

  • React Component Lifecycle: Certain React component lifecycle methods, like `componentDidMount`, are run only on the client side. If code that depends on `document` is placed in methods or components likely to run during server rendering, it will cause the error.
  •  

  • Environment-Specific Code Execution: The presence of code that assumes a browser environment without checks for server-side execution causes issues. Conditional code execution is necessary to differentiate between client and server environments.
  •  

  • Using External Libraries: Sometimes, third-party libraries assume a browser environment by default and attempt to use the `document` object without any checks. This can also trigger the error during SSR in Next.js.

 

// An example of a common mistake in using document in Next.js

function Component() {
    const element = document.getElementById('my-element'); // This line will cause an error during SSR
    return <div>My Element</div>;
}

export default Component;

 

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 Unhandled Rejection (ReferenceError): document is not defined in Next.js

 

Fixing "document is not defined" Error

 

  • Since Next.js is a framework for server-side rendering (SSR), it means that certain browser-specific global variables like document do not exist on the server. Therefore, you need to ensure that any code referencing document executes only in the client-side context.
  •  

  • Make use of the useEffect hook for safely accessing the document object, which runs only after the component has been rendered on the client side.

 

import { useEffect } from 'react';

const MyComponent = () => {
  useEffect(() => {
    // Code using document, window, etc. here
    document.title = "My Page Title";
  }, []);
  
  return <div>Hello World</div>;
};

 

Conditional Checking

 

  • Check if the document is defined before using it. Ensure the code is executed only in a browser environment.

 

const myFunction = () => {
  if (typeof document !== 'undefined') {
    // Safe to use document here
    const elem = document.getElementById('myElement');
    // Perform actions on elem
  }
};

 

Dynamic Import

 

  • Consider using next/dynamic to import components that depend on document only on the client side. This method ensures the component is loaded only in the browser, not on the server.

 

import dynamic from 'next/dynamic';

const MyClientSideComponent = dynamic(() => import('./MyClientSideComponent'), {
  ssr: false // Disable server-side rendering for this component
});

export default function Page() {
  return <MyClientSideComponent />;
}

 

Modify Custom Document

 

  • If you need to modify document properties like title or meta tags, use the <Head> component provided by Next.js in your pages. This guarantees proper server-side rendering and hydration.

 

import Head from 'next/head';

const HomePage = () => (
  <>
    <Head>
      <title>Home Page</title>
      <meta name="description" content="Welcome to my homepage" />
    </Head>
    <div>Home Page Content</div>
  </>
);

 

Refactoring to Hooks and States

 

  • Refactor your React components to use the state and hooks instead of directly manipulating the DOM using document.

 

import { useState, useEffect } from 'react';

const FunctionalComponent = () => {
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  if (!isMounted) {
    return null;
  }

  return <div>The component has mounted and can now safely use browser APIs.</div>;
};

 

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

Make your life more fun with your AI wearable clone. It gives you thoughts, personalized feedback and becomes your second brain to discuss your thoughts and feelings. Available on iOS and Android.

Your Omi will seamlessly sync with your existing omi persona, giving you a full clone of yourself – with limitless potential for use cases:

  • Real-time conversation transcription and processing;
  • Develop your own use cases for fun and productivity;
  • Hundreds 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

products

omi

omi dev kit

omiGPT

personas

omi glass

resources

apps

bounties

affiliate

docs

github

help