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.
- 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');
});
}- 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>;
}