Skip to content

Highcharts v12 with NextJS #502

Open
@julioxavierr

Description

@julioxavierr

I'm using Highcharts with NextJS and when trying to update to Highcharts v12, I get the following error:

web:build:  ✓ Compiled successfully
   Collecting page data  .TypeError: Cannot read properties of undefined (reading 'createEvent')
web:build:     at j (/project/node_modules/.pnpm/[email protected]/node_modules/highcharts/highcharts.js:9:2038)
web:build:     at setOptions (/project/node_modules/.pnpm/[email protected]/node_modules/highcharts/highcharts.js:9:16987)
web:build:     at Object.compose (/project/node_modules/.pnpm/[email protected]/node_modules/highcharts/highcharts-more.js:9:23390)

From my research, it seems that this issue might be caused by trying to instance a chart on the server-side, which didn't seem to happen before.

While looking at the README of the project, I noticed that the following section was updated with a comment to only init modules if the Highcharts version is below v12.

highcharts-react/README.md

Lines 423 to 436 in 11c276d

### How to add a module?
To add a module, import it like so:
```jsx
import Highcharts from 'highcharts'
import highchartsGantt from "highcharts/modules/gantt"; // The Gantt module
import HighchartsReact from 'highcharts-react-official'
// Init the module (only for Highcharts v < 12)
if (typeof highchartsGantt === 'function') {
highchartsGantt(Highcharts);
}
```

However, the NextJS section still says the module should be initiated:

highcharts-react/README.md

Lines 140 to 155 in 11c276d

### Highcharts with NextJS
Next.js executes code twice - on server-side and then client-side. First run is done in an environment that lacks `window` and causes Highcharts to be loaded, but not initialized. Easy fix is to place all modules inits in a `if` checking if Highcharts is an object or a function. It should be an object for modules initialization to work without any errors, so code like below is an easy fix:
```jsx
import React from 'react'
import Highcharts from 'highcharts'
import HighchartsExporting from 'highcharts/modules/exporting'
import HighchartsReact from 'highcharts-react-official'
if (typeof Highcharts === 'object') {
HighchartsExporting(Highcharts)
}
...
```

Which approach should be followed for NextJS? Could the server-side instance attempt be caused by something else?

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions