ionorg / ion-sdk-js

ion javascript sdk
MIT License
102 stars 70 forks source link

NextJS ReferenceError: MediaStream is not defined #229

Closed mattjslaton closed 1 year ago

mattjslaton commented 2 years ago

Library installs fine, but when I go to import anything from 'ion-sdk-js' I get the message, "ReferenceError: MediaStream is not defined" is this a normal bug when using this library with NextJS? Any workarounds? I would love to get it working with my NextJS project. Thanks

lakshmanpasala commented 2 years ago

Are you importing this sdk in SSR component? I would suggest you use dynamic import to load this only on the client-side. e.g.

import { useEffect } from 'react';
import dynamic from 'next/dynamic';
import { Client, LocalStream, RemoteStream } from 'ion-sdk-js';
import { IonSFUJSONRPCSignal } from 'ion-sdk-js/lib/signal/json-rpc-impl';

const IonComponent = () => {
  useEffect( async() => {
    const signal = new IonSFUJSONRPCSignal("wss://ion-sfu:7000/ws");
    const client = new Client(signal);
    signal.onopen = () => client.join("test session", "test uid");

    signal.onopen = () => client.join("test session", "test uid")

    // Setup handlers
    client.ontrack = (track: MediaStreamTrack, stream: RemoteStream) => {
        // mute a remote stream
        stream.mute()
        // unmute a remote stream
        stream.unmute()

        if (track.kind === "video") {
            // prefer a layer
            stream.preferLayer("low" | "medium" | "high")
        }
    };

    // Get a local stream
    const local = await LocalStream.getUserMedia({
        audio: true,
        video: true,
        simulcast: true, // enable simulcast
    });

    // Publish stream
    client.publish(local);

    return () => {
      client.close();
    }
  }, []);

  return
};

export default dynamic(() => Promise.resolve(IonComponent), { ssr: false });
jason-shen commented 2 years ago

here is a little tip for you for nextjs, try to wrap the component that has the ion-sdk-js in a second level rather than call it straight, as nextjs is a server side thing it doesn't not have the browser stuff until its fully loaded