MutationObserver Is Not Defined in Next.js
Next.js pre-renders pages on the server where MutationObserver doesn't exist. If a component or library tries to access it during SSR, you get ReferenceError: MutationObserver is not defined.
The Cause
This happens when:
- A third-party library initializes a
MutationObserverat import time - Your code references
MutationObserveroutside ofuseEffect - A tooltip, popover, or rich text editor library requires the DOM on import
Fix 1: useEffect Guard
import { useEffect, useRef } from 'react';
export function AutoResizeTextarea() {
const ref = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
if (!ref.current) return;
const observer = new MutationObserver(() => {
ref.current!.style.height = 'auto';
ref.current!.style.height = ref.current!.scrollHeight + 'px';
});
observer.observe(ref.current, { childList: true, characterData: true });
return () => observer.disconnect();
}, []);
return <textarea ref={ref} />;
}Fix 2: Dynamic Import for Libraries
If a third-party library uses MutationObserver at module level:
import dynamic from 'next/dynamic';
const RichEditor = dynamic(() => import('@/components/RichEditor'), {
ssr: false,
loading: () => <div>Loading editor...</div>,
});Fix 3: typeof Check
const hasMutationObserver = typeof MutationObserver !== 'undefined';
function observeChanges(element: HTMLElement) {
if (!hasMutationObserver) return;
const observer = new MutationObserver(handleMutations);
observer.observe(element, { subtree: true, childList: true });
}Bugsly captures SSR errors in Next.js including ReferenceError for browser APIs, showing which page route triggered the server-side rendering failure.
Try Bugsly Free
Track up to 100 issues per month on the free plan, with unlimited events and no credit card required.
Get Started FreeRelated Articles
How to Fix Null Reference in R
Learn how to diagnose and fix the null reference in R. Includes code examples and prevention tips.
Read moreFix SyntaxError in PHP
Step-by-step guide to fix SyntaxError in PHP. Includes root cause analysis, code examples, debugging tips, and prevention strategies.
Read moreFix SyntaxError in C# In Production
Step-by-step guide to fix SyntaxError in C# In Production. Includes root cause analysis, code examples, debugging tips, and prevention strategies.
Read moreHow to Fix Undefined Variable in Gatsby
A practical guide to resolving Undefined Variable in Gatsby, with real code examples and debugging tips.
Read more