All posts

Fix IntersectionObserver Error in Deno

Resolve IntersectionObserver reference errors when running browser-targeted code in Deno's server-side runtime environment.

IntersectionObserver Is Not Defined in Deno

If you're running code in Deno that references IntersectionObserver, you'll hit a ReferenceError: IntersectionObserver is not defined. This happens because IntersectionObserver is a browser-only API — it doesn't exist in Deno's server runtime.

Why This Happens

This typically surfaces when:

  • You're doing server-side rendering (SSR) with a framework like Fresh or Aleph.js
  • A shared utility module imports browser code unconditionally
  • A third-party npm package assumes a browser environment

The Fix

Guard browser API access with an environment check:

// utils/observer.ts
export function createObserver(element: Element, callback: () => void) {
  if (typeof IntersectionObserver === "undefined") {
    // Server-side: skip or use a fallback
    console.warn("IntersectionObserver not available in this environment");
    return null;
  }

  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        callback();
      }
    });
  });

  observer.observe(element);
  return observer;
}

In Fresh specifically, wrap observer logic inside useEffect in an island component — islands only run on the client:

import { useEffect, useRef } from "preact/hooks";

export default function LazyImage({ src }: { src: string }) {
  const ref = useRef<HTMLImageElement>(null);

  useEffect(() => {
    const obs = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting && ref.current) {
        ref.current.src = src;
      }
    });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);

  return <img ref={ref} alt="" />;
}

Bugsly can track these ReferenceError exceptions in your Deno deployment, helping you find every spot where browser APIs leak into server code.

Try Bugsly Free

Track up to 100 issues per month on the free plan, with unlimited events and no credit card required.

Get Started Free