Skip to content

Instantly share code, notes, and snippets.

@wuriyanto48
Created August 12, 2025 01:31
Show Gist options
  • Select an option

  • Save wuriyanto48/a3091322ff9ad26f4541393fb21b6a85 to your computer and use it in GitHub Desktop.

Select an option

Save wuriyanto48/a3091322ff9ad26f4541393fb21b6a85 to your computer and use it in GitHub Desktop.
Nextjs Avoid: Referenceerror: document is not defined

This error is relatively undetectable because when the page loads, it appears as if nothing is happening. However, when you open Developer Tools, you'll see that it actually returns a 500 Internal Server Error.

Usually caused by accessing documents in SSR code.

// NextJs SSR Code: for example
const { referrer } = document;

.....
const element = document.getElementById('my-element');

Caution: the document and window only exist in the browser, so if called in code running on the server (SSR), it will definitely give an error.

To resolve this error, ensure that any code relying on the document object is executed only on the client-side. Here are common solutions: Conditional Rendering with typeof window.

  1. Wrap the code that accesses document within a conditional check to ensure it only runs in a browser environment.
if (typeof window !== 'undefined') {
      // Code that uses 'document' here
      document.addEventListener('DOMContentLoaded', () => {
        console.log('DOM fully loaded and parsed');
      });
    }
  1. Using the useEffect Hook.
import { useEffect } from 'react';

    function MyComponent() {
      useEffect(() => {
        // Code that uses 'document' here
        const element = document.getElementById('my-element');
        // ...
      }, []); // Empty dependency array ensures it runs only once after initial render
      return <div>...</div>;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment