All posts

Fix MutationObserver Error in Next.js

Resolve MutationObserver reference errors in Next.js SSR by properly guarding browser APIs and using dynamic imports.

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 MutationObserver at import time
  • Your code references MutationObserver outside of useEffect
  • 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

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free