I import a chart/map library and the build or page crashes with ReferenceError: window is not defined or document is not defined. How do I load it only on the client?
#nextjs#ssr#window#dynamic-import
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
I import a chart/map library and the build or page crashes with ReferenceError: window is not defined or document is not defined. How do I load it only on the client?
#nextjs#ssr#window#dynamic-import
Server rendering runs in Node, where window and document do not exist. Some libraries touch them at import time.
ssr: falsessr: false must be used inside a client component (in Next 15 it is not allowed directly in server components).
"use client";
import dynamic from "next/dynamic";
const Map = dynamic(() => import("./map"), {
ssr: false,
loading: () => <div className="h-64 animate-pulse bg-gray-100" />,
});
export default function MapSection() {
return <Map />;
}
Then import MapSection from your server page.
Browser APIs are safe inside useEffect or event handlers because they only run in the browser:
useEffect(() => {
const w = window.innerWidth;
// ...
}, []);
useEffect(() => {
import("some-lib").then((m) => m.init(ref.current!));
}, []);
const isBrowser = typeof window !== "undefined";
Do not use this result to change what you render in the first pass, or you cause hydration errors. Use state set in an effect.
ssr: false removes its SEO value. Isolate the widget only.transpilePackages: ["pkg"] in next.config.import "server-only".Pitfall: localStorage reads inside useState(() => localStorage.getItem(...)) run on the server and crash. Read it in an effect, or see a ready-made hook in the DEV3 snippet library.