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
AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.
Get Started FreeRelated Articles
How to Fix Permissionerror in Express In Production
Learn how to diagnose and fix the permissionerror in Express in production. Includes code examples and prevention tips.
Read moreFix Routing Error in Next.js
Step-by-step guide to fix Routing Error in Next.js. Includes root cause analysis, code examples, debugging tips, and prevention strategies.
Read moreHow to Fix Permission Denied in React
Learn how to diagnose and fix the permission denied in React. Includes code examples and prevention tips.
Read moreHow to Fix Validationerror in TypeScript When Deploying
Learn how to diagnose and fix Validationerror errors in TypeScript when deploying. Step-by-step guide with code examples.
Read more