Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chartjs plugin zoom Reference error: window is not defined

In Nextjs application while I'm run the command for build and export there was an ReferenceError

I've attached the screenshot for your reference..

When remove the import of chartjs-plugin-zoom from the project, the build and export works properly.. enter image description here

like image 644
sathish kumar Avatar asked Oct 16 '25 21:10

sathish kumar


2 Answers

In my case, I had to slightly modify the solution from skorphil. If you try to register the zoom plugin outside the component you will still get the same error. That's why you need to do it inside the component as following:

useEffect(() => {
if (typeof window !== "undefined")
  import("chartjs-plugin-zoom").then((plugin) => {
    ChartJS.register(plugin.default);
  });
}, []);

This makes sure that the plugin code will not run in the server.

like image 58
Begatim Avatar answered Oct 19 '25 13:10

Begatim


This is because nextjs by default use server-side rendering. And zoom-plugin requires window object, but it is not available since the component is rendered on a node.

To make work component which relies on browser API , next/dynamic import can be used

chart-with-zoom.jsx

import zoomPlugin from 'chartjs-plugin-zoom'; // require window in order to be imported

ChartJS.register(zoomPlugin)

export default function ChartZoom() {
...

app.jsx

import dynamic from 'next/dynamic';

const ChartZoom = dynamic(() => import('PATH TO chart-with-zoom'), {
  ssr: false, // Disable server-side rendering
});

...
return <ChartZoom />
like image 30
skorphil Avatar answered Oct 19 '25 13:10

skorphil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!