0

I am getting "ReferenceError: window is not defined" in nextjs; every time i refresh the page while Agora is imported, it only happens when the Agora sdk is imported; which would suggest it has something to with it. I have tried using next/dynamic to import without ssr, but it shows "Not a function". Maybe i am not doing it well?

Here is where it is imported in(settings.js):

import { createClient, createMicrophoneAudioTrack } from "agora-rtc-react";

const appId = "***";
const token = null;

export const config = { mode: "rtc", codec: "vp8", appId: appId, token: token };
export const useClient = createClient(config);
export const useMicrophoneAudioTrack = createMicrophoneAudioTrack();
export const channelName = "Main";

Here is where i use it(room.jsx):

const client = useClient();
const { ready, track } = useMicrophoneAudioTrack();

It works perfectly when i just enter the page, but if i refresh it i get the "Window is not defined" error.

please can someone help? i have been stuck for quite a while now

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Jeoffrey Duke
  • 143
  • 1
  • 11
  • You should create a component to encapsulate the `agora-rtc-react` logic, then dynamically load that component using `next/dynamic` with `{ ssr: false }`. Check the official Next.js example: https://github.com/AgoraIO-Community/Agora-RTC-React/tree/master/example/nextjs. – juliomalves Jul 29 '22 at 19:43

1 Answers1

1

At the first rendering, window is not exist.

Please put your code in "componentDidMount" or you need to check manually:

const hasWindow = typeof window !== 'undefined'

if (hasWindow) {
  // your code
}
Guti
  • 81
  • 4