Published on December 13th, 2024
When working with Next.js, you may come across the error ReferenceError: document is not defined
or ReferenceError: window is not defined
. This issue arises because the document
object is not available on the server-side.
Next.js uses server-side rendering (SSR) to make your site render faster. As a result, it attempts to render pages on the server before sending them to the client browser. Objects like document
, window
, or localStorage
are part of the browser's runtime environment and are unavailable during server-side rendering.
ReferenceError: document is not defined
ReferenceError: window is not defined
| Context | Access to document
| Access to window
| Access to localStorage
|
|--------|-------|--------|-------|
| Server-side | ❌ Not available | ❌ Not available | ❌ Not available |
| Client-side | ✅ Available | ✅ Available | ✅ Available |
The document
or window
object and other APIs are part of the browser’s environment. When you attempt to use them during the server-side rendering phase, they do not exist, leading to the error.
To fix this issue, you have to make sure that the code only runs on the browser. One effective method is to use a typeof
check to confirm if document
or window
exists before attempting to access it.
typeof document !== 'undefined' && document.querySelector('escapism');
typeof window !== 'undefined' && console.log(window.innerWidth);
If you prefer, you can wrap your code in a useEffect
hook, which only runs on the client after the component mounts.
import { useEffect } from 'react';
const MyComponent=() {
useEffect(() => {
const meElement = document.querySelector('escapism');
// Your browser-dependent/client-side code here
}, []);
return <div>whaalever</div>;
}
import dynamic from 'next/dynamic';
const ComponentWithBrowserCode = dynamic(() => import('./MyComponent'), { ssr: false });
The 'document is not defined'
or 'window is not defined'
error in Next.js arises due to the server-side rendering process, where browser-specific APIs are unavailable. To fix it:
typeof
checks to ensure the code runs in the browser.useEffect
for client-side execution.