I'm stuck while trying to create an xterm React component in Next.js because I can't get over an error message I've never received before.
I'm trying to import an npm client module called xterm
, but if I add the import line, the application crashes.
import { Terminal } from 'xterm'
Error reading Server error... ReferenceError: self is not Defined
Then display this code as Source
module.exports = require("xterm");
From some research I've done, this has to do with Webpack and it might be helpful if something like this is done:
output: { globalObject: 'this' }
Do you know how to solve this problem?
This error occurs because the library requires Web API to work, and when Next.js prerenders the page on the server side.
In your case,
xterm
is trying to access awindow
object that does not exist on the server. The solution is to avoid loadingxterm
on the server and import it dynamically so that it is only loaded on the client.In Next.js, there are multiple ways to achieve this.
#1 Use dynamic
import()
inside
useEffectMove
import
to the component'suseEffect
, then dynamically import the library and add logic there.#2 Use
next/dynamic
withssr: false
Create a component and add
xterm
logic to it.Then dynamically import the component when used.
As an alternative, you can add logic directly when using
next/dynamic
to dynamically import the library to avoid generating extra files.