Walkthrough
JavaScript

Migrating JavaScript SDK to v2 (2.x.x)

This guide will help you migrate your existing JavaScript SDK i.e. 0.x.x to the new 2.x.x version.

Installation

If you are using commonjs or esm, you can install the latest version of the SDK using the following command

pnpm i @huddle01/web-core@latest

If you are using iife or umd, you can use the following script tag to load the latest version of the SDK.

<script src="https://unpkg.com/@huddle01/web-core@latest/dist/index.global.js"></script>

Initialization

All methods of the SDK will be accessible from huddleClient. First you need to create a new instance of HuddleClient where you need to pass projectId.

💡

You can retrieve your projectId from API Keys Page by just connecting your wallet.

If you are using commonjs you can import HuddleClient using require.

import { HuddleClient } from '@huddle01/web-core';
 
const huddleClient = new HuddleClient({
  projectId: 'YOUR_PROJECT_ID',
}); 

Room Creation

You need a roomId for joining a room, which you can get by calling the Create Room API. Make sure that you are calling this API from server side. You can create an API route in a separate Next.js web app or create an Express server.

pages/api/create-room.ts
import axios from 'axios';
import type { NextApiRequest, NextApiResponse } from 'next';
 
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  try {
    const { data } = await axios.post(
      'https://api.huddle01.com/api/v1/create-room',
      {
        title: 'Huddle01 Meet',
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'x-api-key': process.env.API_KEY as string,
        },
      }
    );
 
    res.status(200).json(data);
  } catch (error) {
    res.status(500).json(error);
  }
};
 
export default handler;

Authentication (Generating Access Token)

In 2.x.x version of SDK, you need an accessToken to join a room, without that you can't join a room using joinRoom method. To generate an accessToken you need to use our Server SDK

⚠️

Use Server SDK on server side only, don't use it on client side.

You can create an API route in a separate Next.js web app or create an Express server to generate accessToken.

pages/api/getAccessToken.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { AccessToken, Role } from '@huddle01/server-sdk/auth';
 
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { roomId } = req.query;
 
  if (!roomId) {
    return res.status(400).json({ error: 'roomId is required' });
  }
 
  const accessToken = new AccessToken({
    apiKey: process.env.API_KEY!,
    roomId: roomId as string,
    role: Role.HOST,
    permissions: {
      admin: true,
      canConsume: true,
      canProduce: true,
      canProduceSources: {
        cam: true,
        mic: true,
        screen: true,
      },
      canRecvData: true,
      canSendData: true,
      canUpdateMetadata: true,
    }
  });
 
  const token = await accessToken.toJwt();
 
  return res.status(200).json({ token });
}

Joining/Leaving Room

With our newer SDK i.e. 2.x.x, we have streamlined the process by eliminating the additional step of joining a lobby before entering a room. You can now directly join a room using joinRoom method accessible through huddleClient. It requires two parameters roomId and token both of which have been generated in previous steps.

You can call the APIs which we have created in previous steps to get roomId and token.

// Use the `huddleClient` instance created in previous steps 
document.getElementById('joinRoom').onclick = async () => {
    await huddleClient.joinRoom({
        roomId: "YOUR_ROOM_ID",
        token: "YOUR_ACCESS_TOKEN"
    });
};
 
document.getElementById('leaveRoom').onclick = async () => {
    await huddleClient.leaveRoom();
};

Producing Audio/Video

In 2.x.x version of SDK, you don't need to call enableCam and produceCam methods separately. You can just call enableVideo which will enable your camera and start producing if you have joined room. Similarly, for audio as well you can just call enableAudio which will get your audio stream and it will start producing if you have joined room.

💡

You can also share you screen and consume other peer's screen, to learn more refer to Screen Share.

document.getElementById('enableVideo').onclick = async () => {
    const stream = await huddleClient.localPeer.enableVideo();
 
    // You can use this stream to show your video in UI
    const videoRef = document.getElementById('videoRef');
    videoRef.srcObject = stream;
 
    videoRef.onloadedmetadata = async () => {
      try {
        await videoRef.play();
      } catch (error) {
        console.error(error);
      }
    };
};
 
document.getElementById('disableVideo').onclick = async () => {
    await huddleClient.localPeer.disableVideo();
};
 
document.getElementById('enableAudio').onclick = async () => {
    await huddleClient.localPeer.enableAudio();
};
 
document.getElementById('disableAudio').onclick = async () => {
    await huddleClient.localPeer.disableAudio();
};

Showing Remote Peers

In 2.x.x version of SDK, you can get remotePeers from huddleClient.room. remotePeers is a Map<string,RemotePeer>, where string is a peerId and RemotePeer is an object. Once, you have access to RemotePeer object, you can get media streams and other information of that peer such as it's metadata.

With 2.x.x we have remove methods like setAvatarUrl and setDisplayName, instead of these you can set any type of metadata for a peer.

💡

You can refer to RemotePeer and LocalPeer to learn more.

// This will listen to new peer joined event
huddleClient.room.on("new-peer-joined", () => {
  huddleClient.room.remotePeers.forEach((peer) => {
    // metadata can be any type of data
    console.log(peer.metadata);
    // role
    console.log(peer.role);
  });
});

Consuming Audio/Video

In 2.x.x version of SDK, to access stream of a remotePeer you need to access consumer and then you can get a stream from it.

// Listen to `stream-added` event 
huddleClient.room.on("stream-added", ({ peerId, label }) => {
    const container = document.querySelector("#remotePeers");
    let mediaRef = document.createElement("video");
    if (label == "audio") {
      mediaRef = document.createElement("audio");
    }
    const remoteTrack = client.room
      .getRemotePeerById(peerId)
      ?.getConsumer(label)?.track;
 
    mediaRef.srcObject = new MediaStream([remoteTrack]);
    mediaRef.id = `${peerId}-${label}`;
    mediaRef.autoplay = true;
    if (label == "video") {
      mediaRef.muted = true;
    }
    mediaRef.className = "border-2 rounded-xl border-white-400 aspect-video";
    container.appendChild(mediaRef);
});
 
huddleClient.room.on("stream-closed", ({ peerId, label }) => {
    const mediaRef = document.querySelector(`#${peerId}-${label}`);
    mediaRef.srcObject.getTracks().forEach((track) => track.stop());
    mediaRef.srcObject = null;
    mediaRef.remove();
});

Sending/Receiving Data

In 2.x.x version of SDK, you can send data using sendData method from huddleClient.localPeer and receive data by listening to receive-data event.

💡

You can also pass label while sending data, which will help you to identify the type of data while receiving.

document.getElementById('sendData').onclick = async () => {
    huddleClient.localPeer.sendData({
        to: "*",
        payload: "gm!",
        label: "greet"
    });
};
 
// listen to `receive-data` event
huddleClient.localPeer.on('receive-data', (data) => {
    console.log(data.label, data.payload);
});

Happy Hacking 🎉

You can refer to the following sample apps build on Javascript SDK

Congratulations! If you have followed this guide till here, we hope that you have successfully migrated to 2.x.x

Audio/Video Infrastructure designed for the developers to empower them ship simple yet powerful Audio/Video Apps.
support
company
Copyright © 2024 Graphene 01, Inc. All Rights Reserved.