Error: global is not defined - when creating a matrix client
Matrix SDK is not compatible with the latest version of Next.js (14.2.15). Creating a client causes an error in the amendClientOpts function, where it uses the global variable, which is not defined in this environment. The error started occurring with matrix-js-sdk version 34.4.0. The error appears on this line, but the global variable is used multiple times.
The code is simple. Here’s an example.
"use client";
import { createClient, MatrixClient } from "matrix-js-sdk";
import React, { useEffect, useRef } from "react";
export default function HomePage() {
const matrixClient = useRef<MatrixClient | null>(null);
useEffect(() => {
matrixClient.current = createClient({ baseUrl: "https://matrix.org" });
}, []);
return <div>page</div>;
}
Here, I have a screenshot of the error.
The browser recognizes globalThis but not global. global is available only in a node.js environment. How can I run Matrix on Next.js? Thanks in advance for the help.
I think matrix-js-sdk currently expects the environment to provide a polyfill for global. For example, Weback provides one.
I am very surprised that you found this started with 34.4.0, because as far as I know this code has not changed in years.
As for solutions: pull-requests to replace global with globalThis would be welcome.
In the meantime, maybe you can work around it. I'm not familiar with next.js but maybe you can configure it to provide a polyfill? Alternatively, if you provide a concrete implementation of IStore to createClient, you'll avoid the problematic line:
let store = new MemoryStore({ localStorage });
let client = createClient({ store });
I've noticed that this started breaking somewhere in the vicinity of v33.0.0-v34.0.0. Building and running our application on v32.4.0 didn't result in an error, but v33.x.x resulted in https://github.com/matrix-org/matrix-js-sdk/issues/4284, and v34.0.0 results in the error as described above.
Something did change.
I've noticed that this started breaking somewhere in the vicinity of v33.0.0-v34.0.0. Building and running our application on v32.4.0 didn't result in an error, but v33.x.x resulted in #4284, and v34.0.0 results in the error as described above.
Something did change.
That's very confusing. If you look at, say, lib/matrix.js in https://www.npmjs.com/package/matrix-js-sdk/v/32.4.0?activeTab=code, you can clearly see the reference to global.localStorage :/
It is indeed quite odd. My guess is that something was changed in the way the library was exported? There were some changes to export as an ESM module, I wonder if that impacts the way global is defined.
Either way, I'll progress trying to move away from global so the next release should be fine.