Next.js: `window is not defined` error when importing a chart library
poze 4 months ago578 gadeen
I import a charting library in a page and the build fails with ReferenceError: window is not defined. The component has 'use client' at the top. Why is it still running on the server?
Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
1 Repons
'use client' doesn't mean "browser only". Client Components are still pre-rendered on the server to produce the initial HTML. Any library that touches window when it's *imported* will crash there.
Load it only in the browser with next/dynamic and ssr: false:
'use client';
import dynamic from 'next/dynamic';
const Chart = dynamic(() => import('./Chart'), {
ssr: false,
loading: () => <p>Loading chart…</p>,
});
ssr: false must be used inside a Client Component. If you only access window in your own code, move that access into a useEffect instead.
Konekte pou di lòt moun si li te mache.
Sign in and verify your email to post an answer.