Search code examples
javascriptreactjsnext.jsserver-side-renderingapexcharts

React/Next.js doesn't seem to work with Apexcharts


Problem

My Next.js/React/Node app crashes when I import Chart from "react-apexcharts" in any file. Attempting to visit the app results in the following error:
Server Error
ReferenceError: window is not defined
This error happened while generating the page. Any console logs will be displayed in the terminal window.
(see call stack below).
This happens regardless if the imported <Chart/> is rendered in the page or just left unused. Interesting thing is, if I save a file and initiate a Next.js quick refresh, my app begins working as normal (sometimes). But, when I just launch the app and attempt to visit it, or when I manually refresh with f5, the aforementioned error occurs. Basically, it only works after a Next.js quick refresh (and sometimes, presumably randomly, it doesn't work in this scenario either, throwing the same error as before).

Environment

Node.js (14.16.0), React (17.0.2), Express (4.17.1), Next.js (10.2.0), react-apexcharts (1.3.9), apexcharts (3.26.3), Edge Browser, Win10.
Next.js server is integrated together with Express server.

Logging

ReferenceError: window is not defined
    at Object.<anonymous> (C:\Users\georg\Documents\development\web\projects\Angelina-Website\node_modules\apexcharts\dist\apexcharts.common.js:6:345884)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)   
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)        
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)     
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (C:\Users\georg\Documents\development\web\projects\Angelina-Website\node_modules\react-apexcharts\dist\react-apexcharts.min.js:1:722)      
    at Module._compile (internal/modules/cjs/loader.js:1063:30)   
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)        
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)     
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.react-apexcharts (C:\Users\georg\Documents\development\web\projects\Angelina-Website\.next\server\pages\partner\dashboard.js:4973:18)
    at __webpack_require__ (C:\Users\georg\Documents\development\web\projects\Angelina-Website\.next\server\webpack-runtime.js:25:42)

Solution

  • The above issue appears because you created the next.js app with SSR enabled

    To solve this issue, you need to import the apex-charts component dynamically with SSR disabled.

    import dynamic from 'next/dynamic'
        
    const Chart = dynamic(() => import('react-apexcharts'), { ssr: false });