[Vuejs]-Can not read property "document" of undefined – ApexCharts

6πŸ‘

βœ…

This is because you are using Nuxt.js which does SSR for you. Since document does not exist on the server-side it will break.

To work around it there a couple of approaches:

First you can create a plugin/apex.js which is responsible for registering your components

import Vue from 'vue';
import ApexChart from 'vue-apexcharts';

Vue.component('ApexChart', ApexChart);

and in your nuxt.config.js make sure to load the plugin file on the client-side:

module.exports = {
  // ...
  plugins: [
    // ...
    { src: '~/plugins/charts', ssr: false }
  ],
  // ....
};

Now you can reference the ApexChart component anywhere in your app, also make sure to wrap it with ClientOnly component to prevent Nuxt from attempting to render it on the server-side:

<ClientOnly>
  <ApexChart type="donut" :options="chartData.options" :series="chartData.series" />
</ClientOnly>

The other approach is you can import Apex charts as async components, which do not get rendered on the server-side, but it has been a hit and miss with this approach, feel free to experiment.

Generally when using Nuxt or any SSR solution, be careful of the libraries you use as they might have an implicit dependency on the execution environment, like requiring browser-specific APIs in order to work like window or document.

πŸ‘€logaretm

Leave a comment