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

posée 4 months ago585 vuesen

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?

Environnement :Next.js 15

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 4 months ago

1 réponse

4
✓
✓ Réponse acceptée

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

Connectez-vous pour dire si ça a marché.

answered 4 months ago

Sign in and verify your email to post an answer.