Solved

Next.js: "window is not defined" after adding a chart library

Asked by Arjun Rao · 533 views · 2 replies

Arjun Rao4 messages

Installed a charting package, imported it in my dashboard page, and the build fails with ReferenceError: window is not defined. The component already has "use client" at the top. I thought that meant it runs in the browser?

2 replies

Daniela RochaSolution

It runs in the browser as well. A Client Component is still rendered once on the server to produce the first HTML, and only then hydrated in the browser. Any library that touches window when it is imported blows up during that server pass.

Two fixes, depending on where the browser-only code is.

Your own code uses window: move it into useEffect, which only runs in the browser.

A library uses it on import: load it only on the client with next/dynamic:

"use client";
import dynamic from "next/dynamic";

const Chart = dynamic(() => import("./Chart"), { ssr: false });

Note that ssr: false has to be inside a Client Component. In a Server Component, Next refuses it with an error, which confuses a lot of people.

Link
Arjun Rao

Wrapped the chart in its own file and loaded it with dynamic. Build passes. I had completely misunderstood what "use client" meant.

Link