Next.js: `window is not defined` error when importing a chart library
asked 4 months ago580 viewsen
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?
AI diagnosis
AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.
1 Answer
'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.
Sign in to tell others whether this worked.
Sign in and verify your email to post an answer.