Next.js: `window is not defined` error when importing a chart library

poze 4 months ago579 gadeen

6

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?

Anviwònman:Next.js 15

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.

poze 4 months ago

1 Repons

4
✓
✓ Repons yo aksepte

'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.

answered 4 months ago

Sign in and verify your email to post an answer.