Fixing ReferenceError: window is not defined in ApexCharts Next.js 14
ApexCharts is a popular open-source charting library that provides a simple and flexible way to add charts to your web applications. When using ApexCharts with Next.js 14, you might encounter the following error:
ReferenceError: window is not defined
This error occurs because ApexCharts uses the window object, which is not available on the server-side during the initial render of a Next.js application. In this article, we will discuss the causes of this issue and provide solutions to fix it.
Understanding the Issue
Next.js is a universal JavaScript framework that allows you to build server-side rendered (SSR) web applications. This means that the initial HTML of a page is generated on the server-side and then sent to the client-side for further processing. However, some libraries, like ApexCharts, are designed to work only on the client-side and rely on the window object, which is not available on the server-side.
When Next.js tries to render the ApexCharts component on the server-side, it encounters the window object, which is not defined, and throws a ReferenceError.
Solutions
To fix this issue, you need to ensure that the ApexCharts component is only rendered on the client-side. Here are a few solutions to achieve this:
Using Next.js Dynamic Imports
Next.js provides a built-in way to load modules on the client-side using dynamic imports. You can use this feature to load the ApexCharts component only on the client-side, like this:
import dynamic from 'next/dynamic'
const ApexChart = dynamic(() => import('apexcharts-react'), { ssr: false })
function MyChart() {
return (
)
}
export default MyChart
Using Next.js withReact.lazy
You can also use the React.lazy feature to load the ApexCharts component only on the client-side, like this:
import React, { lazy, Suspense } from 'react'
const ApexChart = lazy(() => import('apexcharts-react'))
function MyChart() {
return (
Loading...