A Developer’s Intro to Huddle01 SDK and Ideas to Build
Table of contents
- Introduction
- Huddle01's two sided Marketplace.
- What is Huddle01 SDK ?
- Room
- Peer
- MediaStream
- MediaStreamTrack
- Local
- Remote
- Data Message
- Metadata
- Room States
- Why to choose Huddle01 SDKs ?
- What are the offerings from Huddle01 ?
- Recent version update V1.x.x -> V2.x.x.
- How the concepts have changed
- Comparison b/w LTS & Legacy SDK Concepts:
- New SDK Concepts:
- States in Legacy SDK (Deprecated):
- Migrating Hooks from v1 (0.x.x) to v2 (2.x.x)
- How to start building with Huddle01's SDKs ?
- Grabbing the API Key
- Deep Dive into the SDK
- Building a Video Conferencing Room with Screen Sharing
- Some Potential Tool/Project Ideas
- Conclusion
Introduction
Are you a developer?
Building something on RTC (Real Time Communication) ?
Opting WebRTC for your project ?
Wait! I have a better alternative for you.
Introducing to you Huddle01 SDKs.
SDKs to boost your RTC app with dRTC features with web3 native security.
Agenda of this article
Let's have a look on what topics we are going to cover in this article :-
What is Huddle01 ?
Huddle01's two sided Marketplace.
What is Huddle01 SDK ?
Why to choose Huddle01 SDKs ?
What are the offerings from Huddle01 ?
Recent version update V1.x.x -> V2.x.x.
Some project ideas.
How to start building with Huddle01's SDKs and the Resources ?
Conclusion
What is Huddle01 ?
Huddle01 is world's first DePIN (Decentralized Physical Infrastructure Network) dedicated to building dRTC (Decentralized Real Time Communication) infrastructure to provide us more secure and faster Audio/Video communication in a much cheaper price.
Now, in describing Huddle01, I have used many technical abbreviations. Let's first understand these abbreviations to fully grasp what Huddle01 is all about.
DePIN
As I mentioned earlier, the full form of DePIN is Decentralized Physical Infrastructure Network. Now, what does it mean? Let's simplify it with a basic example.
Imagine you work in a large company where many others like you are employed. Based on your work, you receive a fixed or variable salary. This scenario is somewhat like a DePIN. You contribute value or resources—such as time and skills—to the company, and in return, the company rewards you with a salary based on your performance and the value you bring.
In a DePIN setup, picture yourself as a node, and the company as a network of nodes like you. Nodes offer their resources to support the network, and depending on the resources each node contributes, the network incentivize them with crypto tokens.
The key difference between DePIN and the company example is that the company is centralized, meaning it's controlled by individuals or a specific group. In contrast, DePIN operates through people, making it a community-driven network, hence decentralized. This distinction is why it's named the Decentralized Physical Infrastructure Network.
dRTC
RTC stands for Real-Time Communication. Nowadays, we use it everywhere in our daily lives, from chatting or audio/video calling on WhatsApp, playing multiplayer games with friends like BGMI, to even communicating with customer service representatives on platforms like Amazon.
Now, dRTC stands for Decentralized Real-Time Communication. It signifies real-time communication between two or more people (peers) over a decentralized network in a more secure and faster manner.
So, with these information now it is clear that what is Huddle01 right ?
Huddle01's two sided Marketplace.
Before hoping into Huddle01 SDKs let's just understand that how Huddle01's dRTC ecosystem works. So, Huddle01 has a two sided marketplace of supply and demand.
Here, "supply" means, supply of bandwidth or minutes to the dRTC network. This is done by the Media Nodes. These nodes are computing devices (like PCs, Laptops etc.) that shares their unused bandwidth and computing resources to power the dRTC network of Huddle01. And in return they are incentivised by Huddle01's native token $HUDL.
Now, "demand" means the need or consumption of these shared bandwidth and resources. The Huddle01 dApp and the SDKs consumes these bandwidth to use the dRTC infrastructure and provide us the real-time Audio/Video communication feature. Here, the peers who uses Huddle01 dApp or platform to do their meets also get incentivised by $HUDL.
There are two more crucial roles present those are as important as the Media Nodes and Peers. These are, Orchestrators and Validators.
As an Orchestrator, you can earn rewards ($HUDL) for matching media nodes to participants and coordinating meeting rooms.
As a Validator, you earn rewards (&HUDL) for validating dRTC execution transactions. As Huddle01’s employs a proof-of-stake consensus mechanism, you can earn rewards through staking.
Note : These features and roles will start to work once the mainnet of Huddle01 release. For now, these roles are in the testing phase and only few team members are operating the nodes.
What is Huddle01 SDK ?
Now before start talking about Huddle01's SDKs let's understand what is a SDK ?
SDK
SDK stands for Software Development Kit. It consists of platform-specific tools for developers. These tools include debuggers, compilers, and libraries needed to create code that works on a particular platform, operating system, or programming language. SDKs gather everything necessary for software development in one location. They also provide resources such as documentation, tutorials, guides, APIs, and frameworks to speed up application development.
Now as we understand what is a SDK, let's deep dive into Huddle01's SDKs.
Huddle01 is currently providing 5 SDKs i.e.
So, we can integrate all the features of Huddle01's Audio/Video Real-Time Communication with our websites using its Vanilla JavaScript or React SDK. For our Android application, we can use React Native SDK, and for cross-platform applications, we can use Flutter SDK. Additionally, we can power A/V RTC within our softwares built with Node.js using Huddle01's server SDK.
Now let's have a look on Huddle01 SDK's core architecture :
This diagram shows the core working principle of Huddle01 SDKs. To gain a deeper understanding, let me describe some concepts and terms that you should be familiar with before using the SDKs into your projects.
Room
A room is a virtual entity inside where you can have Huddle01 meeting sessions. It contains all the participants and their media streams. Each room is identified by a unique roomID that is generated when you create a room. A room does not expire and you can have multiple meeting sessions inside the same room for as long as you want, one meeting session at a time.
Peer
A peer is a participant inside a room. It is an object containing all the media streams of a participant. Each peer is represented by a unique peerId. Every peer is associated with a room.
MediaStream
The MediaStream
interface represents a stream of media content. A stream can consist of several tracks, which can be either audio or video. MediaStreams
are associated with their respective peer.
MediaStreamTrack
The MediaStreamTrack
interface represents a single media track within a MediaStream
. It can be either an audio or a video track.
Local
Once you join a room, all operations related to your own Peer object insde a room are represented by the keyword local.
Item | Variable |
Your Peer Object | localPeer |
Your Audio Stream | localAudio |
Your Video Stream | localVideo |
Remote
All other peers in the same room as you are represented by the keyword remote. Performing any operations related to a remote peer would require you to pass in the peerId of the remote peer.
Item | Variable |
Another Peer Object | remotePeer |
Another Peer's Audio Stream | remoteAudio |
Another Peer's Video Stream | remoteVideo |
Data Message
Besides MediaStreams
, peers in the room can also send messages to one other in the form of text strings not exceeding 280 characters in length. These messages are called data messages.
Metadata
Metadata is a generic object that can be attached to both Peers and the Room itself. It can be used to store any additional information that you want to associate with a Peer or a Room. The SDKs expose methods to get and set these metadata.
Room States
At any given point, a Room can be in any one of these 6 states.
RoomState | Description |
idle | Room is created and ready to be joined |
connecting | You are trying to join the room |
connected | You have joined the room |
failed | You have failed to join the room |
left | You have left the room |
closed | The room has been closed |
Now as we get to know about what is Huddle01's SDKs, let's explore why should we use it.
Why to choose Huddle01 SDKs ?
By stating why we should choose Huddle01 SDKs I meant that why particularly Huddle01 ? Why not any other RTC service providers to approach ?
Let's compare Huddle01 with current market on a same usecase.
usecase : Video meeting for 24/7 with a traffic of 2,000 peers.
Subject | AWS | HUDDLE01 |
Infrastructure | WebRTC | dRTC |
Purchase Compute Power | Fixed Cost, Monopolistic, Extreme data markup prices | Pay-as-you-go, Open Marketplace, Zero data pricing |
Rent network, Optimized instances | Public Cloud charges for both internet & data transfer cost. 10TB consumed for RTC costs ~ $80 | No Premium charge on Data Usage, Pay what you pay for internet, no insane data transfer cost in an open RTC market. |
Cost | Monthly Server Cost: $290,160, Yearly Server Cost: $3,530,280 | Monthly Server Cost: $1000, Yearly Server Cost: $8,920 |
With this table, I believe there's no need for further explanation to show you why we should choose Huddle01 over any other Public Cloud Infrastructure or CPaaS.
But that's not all. Another key difference with Huddle01 compared to other RTC service providers is the tons of features that Huddle01 SDKs provide for you to integrate and use as needed in your project, without any restrictions or extra charges.
Let's now have a look on these features in the next section.
What are the offerings from Huddle01 ?
Features |
Audio Spaces 🎧 |
Recording/Livestreaming 🎥 |
Selective Consuming 📺 |
Collaborative Whiteboard 📝 |
Custom Authentication 🔐 |
Token Gated Rooms🚪 |
Decentralized Ids 🌟 |
Let's have a detailed discussion about these features one-by-one:
Audio Spaces
Audio spaces are one of the most useful features of Huddle01 where we can host an audio conference call. Here, the meeting host can assign specific roles to the attendees such as Co-Hosts, Speakers, and Listeners. These roles are hierarchical, allowing top-order roles to have control over lower roles.
Recording/Livestreaming
Huddle01 SDKs also give you the ability to record videos, screens, and livestream them on various platforms like YouTube, X (Twitter), and more simultaneously. You can see how powerful and versatile these features are. They can even be applied in unexpected scenarios, and we are excited to see new ideas emerging from the Huddle01 ecosystem.
Selective Consuming
Selective consuming is a feature that allows you to receive media streams inside a room, only from the peers that you want. This is useful when you want to mute someone in a meeting only for yourself, or turn off their incoming video, without it affecting other participants.
Collaborative Whiteboard
As the name suggests, the collaborative whiteboard enables peers to access the same whiteboard in their individual spaces, allowing them to contribute or discuss things together. This feature is particularly useful during business calls or for educational purposes.
Custom Authentication
Custom Authentication with Web3Auth enables developers to design personalized authentication flows for their applications. It goes further than standard authentication by allowing customized experiences and data gathering. Huddle01 SDKs incorporate this functionality, guaranteeing smooth user experiences and adaptable authentication approaches.
Token Gated Rooms
We can create a token-gated room using the Create Room API and Room Details. Once we obtain the token gating details, we will verify if the user has the token. If the user has the token, we will generate an access token and allow the user to join the room.
Click here for a more detailed blog on it.
Decentralized IDs
With Huddle01 SDKs you can use Decentralized IDs like Lens, UD, Tezos, ENS, etc, and express yourself, in a decentralized manner to personalize your Huddle01 meetings.
All of these extraordinary unique features are provided by Huddle01 SDKs to incorporate into your upcoming projects for free. Explaining all the features in depth may unnecessarily lengthen this article. Therefore, I have hyperlinked all the documentation links with the feature headings so that you can dive into the vast knowledge pool provided by Huddle01 DEVs.
Now let us explore what changes does Huddle01 V2.x.x brings to the ecosystem.
Recent version update V1.x.x -> V2.x.x.
Huddle01's latest stable version, 2.x.x
, brings significant advancements to the protocol. These include improvements in latency, scalability, network performance, deployments, and reduced re-rendering.
Let's have a look on this one-by-one:
How the concepts have changed
Comparison b/w LTS & Legacy SDK Concepts:
Room - A space where you can conduct meeting sessions containing all participants and their media streams.
Lobby
Legacy: A pre-room staging area for enabling or disabling media streams before joining a room.
New: Deprecated in the new SDK. (Note: You can use APIs now to fetch room user data)
Peer - A participant inside a room with media streams, represented by a unique peerId.
MediaStream - Represents a stream of media content associated with a peer.
MediaStreamTrack - Represents a single media track within a MediaStream.
Produce - Sharing a participant’s media stream with other peers in a room.
Consume - Receiving a peer’s shared media stream inside a room.
App States
Legacy: Four major states - Idle, Initialized, Lobby, Room - with associated methods.
New: Four major updated room states - idle, connecting, connected, failed, left, closed
New SDK Concepts:
Room
- Description: A room is a virtual entity inside which you can have Huddle01 meeting sessions. It contains all the participants and their media streams. Each room is identified by a unique roomID that is generated when you create a room. A room does not expire and you can have multiple meeting sessions inside the same room for as long as you want, one meeting session at a time.
Room States
- States:
idle
,connecting
,connected
,failed
,left
,closed
- Representing different states of a room.
- States:
Local
Description: Operations related to your own Peer object inside a room, represented by the keyword local.
Variables:
localPeer
,localAudio
,localVideo
Remote
Description: Operations related to other peers in the same room, represented by the keyword remote.
Variables:
remotePeer
,remoteAudio
,remoteVideo
Data Message
- Description: Messages sent between peers in the form of text strings not exceeding 280 characters.
Metadata
- Description: A generic object that can be attached to Peers and the Room for storing additional information.
States in Legacy SDK (Deprecated):
Idle/Initialized
- Methods Available:
initialize(projectId: string)
-useHuddle01()
- Methods Available:
Lobby
- Methods Available:
fetchVideoStream()
,fetchAudioStream()
,joinRoom()
,leaveLobby()
,stopVideoStream()
,stopAudioStream()
- CorrespondinguseVideo()
,useAudio()
,useRoom()
hooks.
- Methods Available:
Room
- Methods Available:
produceVideo()
,produceAudio()
,stopProducingVideo()
,stopProducingAudio()
,leaveRoom()
- CorrespondinguseVideo()
,useAudio()
,useRoom()
hooks.
- Methods Available:
Please ensure to refer to the new SDK documentation for detailed information on each concept and its usage.
Migrating Hooks from v1 (0.x.x) to v2 (2.x.x)
Old Hooks Alternatives
Old Hooks | New Hooks |
useRoom | useRoom |
useLobby | useLobby |
usePeers | usePeersIds |
useAudio | useLocalAudio / useRemoteAudio |
useVideo | useLocalVideo / useRemoteVideo |
useScreenShare | useLocalScreenShare / useRemoteScreenShare |
--- | useRoomControls |
--- | useDataMessage |
--- | useDevices |
--- | useActivePeers |
--- | useRoomMetadata |
useHuddle01 | Deprecated |
useAppUtils | Deprecated |
useAcl | Deprecated |
useLivestream | Deprecated |
useRecording | Deprecated |
To gain more information about the changes, click here to be redirected to the official Huddle01 website.
Now the big question comes into our mind that how we can kickstart our journey with Huddle01 SDKs ? Let's discuss in the next section.
How to start building with Huddle01's SDKs ?
To begin your development journey with Huddle01 SDKs, there's no better place than its official documentation. Additionally, Huddle01's official YouTube channel and GitHub repository have plenty of resources for developers to unlock their full potential.
I am sharing all the links here for quick reference.
Huddle01 Official Doc : https://docs.huddle01.com/docs
Huddle01's Official Youtube channel : https://www.youtube.com/@huddle0174
- Huddle01's Official GitHub Repository : https://github.com/Huddle01
But here I’m sharing some code snippets to make you more clear about the SDK integration.
Here’s the correct regenerated part for your post:
Grabbing the API Key
Before you can start building with the Huddle01 SDK, you need to grab an API key by connecting your wallet to the platform. This API key will be used to authenticate and authorize our requests when communicating with the APIs.
Note: You need an Ethereum wallet to access the Huddle01 API Key. I personally recommend using Metamask.
Deep Dive into the SDK
Huddle01 offers several SDKs currently, each suited to different tech stacks. Let’s go through the JavaScript SDK and how to use it.
JavaScript SDK:
You can use the JavaScript SDK in two ways:
Using Script Tags: Add the following script directly to your HTML:
<script src="https://unpkg.com/@huddle01/web-core@umd/dist/index.global.js"></script>
With the JavaScript SDK, you can easily integrate video conferencing and room management functionalities into your web applications.
- Using a package manager (e.g., NPM, Yarn, PNPM, Bun):
npm install @huddle01/web-core
Example Usage:
Using Script Tags (IIFE/UMD):
<script src="https://unpkg.com/@huddle01/web-core@umd/dist/index.global.js"></script>
<script>
let client;
// Call this function on 'Join Room' button click
const init = async () => {
client = new HuddleWebCore.HuddleClient({
projectId: "YOUR_PROJECT_ID",
options: {
activeSpeakers: {
size: 10,
},
},
});
const room = await client.joinRoom({
roomId: "YOUR_ROOM_ID",
token: "YOUR_ACCESS_TOKEN",
});
};
</script>
Using a Package Manager (ESM/CommonJS):
import { HuddleClient } from '@huddle01/web-core';
const huddleClient = new HuddleClient({
projectId: "YOUR_PROJECT_ID"
})
// Call this in onclick of 'Join Room' button
huddleClient.joinRoom({
roomId: "YOUR_ROOM_ID",
token: "YOUR_ACCESS_TOKEN"
});
ReactJS SDK:
The ReactJS SDK has an ample amount of things to offer which you can leverage to play audio streams and show video streams. But before diving in, let us get familiar with some of the common hooks that the SDK has to offer, which will ease our building process:
useRoom
: For joining, leaving, and closing the room.usePeerIds
: Returns peerIds of all peers inside a Huddle01 room.useLobby
: Enables you to manage a virtual waiting room where users can interact.useRoomControls
: Allows you to read and update the room’s controls.useLocalVideo
/useLocalAudio
: To interact with your video/audio streams.useRemoteVideo
/useRemoteAudio
: To interact with other peers’ video/audio streams.useLocalScreenShare
: Allows you to share your screen with other peers.useRemoteScreenShare
: Receive the media stream of another peer’s screen share.useLocalPeer
: Allows you to interact with your own Peer object.useRemotePeer
: Interact with other users’ Peer objects.useDevices
: Interact with the different media devices (camera, microphone, speaker).useActivePeers
: Returns the last most active peers.useDataMessage
: Send and receive messages to and from other peers.useRoomMetadata
: Returns and updates room metadata.
There are also some advanced hooks, check them here.
To use Huddle01’s SDK in your ReactJS/NextJS app, install the required packages:
npm install @huddle01/react
Create a .env
file and paste the Project ID and API_KEY:
# .env
NEXT_PUBLIC_PROJECT_ID="YOUR_PROJECT_ID"
API_KEY="YOUR_API_KEY"
Configuring HuddleProvider
in your root component:
import { HuddleProvider, HuddleClient } from '@huddle01/react';
const huddleClient = new HuddleClient({
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
options: {
activeSpeakers: {
size: 8,
},
},
});
<HuddleProvider client={huddleClient}>
<App />
</HuddleProvider>
Joining Room:
import { useRoom } from '@huddle01/react/hooks';
const { joinRoom } = useRoom({
onJoin: () => {
console.log('Joined room');
}
});
// Join room
joinRoom({
roomId: "YOUR_ROOM_ID",
token: "YOUR_TOKEN"
});
React Native SDK:
Install the package @huddle01/react
and configure the .env
file as you did in the previous section. Then configure HuddleProvider
in your root component:
import { HuddleProvider, HuddleClient } from '@huddle01/react';
const huddleClient = new HuddleClient({
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
options: {
activeSpeakers: {
size: 8,
},
},
});
<HuddleProvider client={huddleClient}>
<App />
</HuddleProvider>
Joining Room:
import { useRoom } from '@huddle01/react/dist/hooks';
const { joinRoom } = useRoom({
onJoin: () => {
console.log('Joined room');
}
});
// Join room
joinRoom({
roomId: "YOUR_ROOM_ID",
token: "YOUR_TOKEN"
});
Flutter SDK:
To get started, install the required packages:
flutter pub add huddle01_flutter_client
Create a Room:
import 'dart:convert';
import 'package:http/http.dart' as http;
String apiKey = "<Generated-from-docs>";
Future<String> createMeeting() async {
final http.Response httpResponse = await http.post(
Uri.parse("https://api.huddle01.com/api/v1/create-room"),
headers: {'Authorization': apiKey},
);
return json.decode(httpResponse.body)['roomId'];
}
Initialize the SDK:
import 'package:huddle01_flutter_client/huddle01_flutter_client.dart';
String projectId = 'YOUR-PROJECT-ID';
String roomId = 'YOUR-ROOM-ID';
HuddleClient huddleClient = HuddleClient(projectId);
huddleClient.joinRoom(roomId, token);
Server-SDK:
The Server SDK facilitates server-side management by enabling access token generation, API calls for creating rooms and live meetings, and programmatic control over recording and live-streaming.
To generate an access token:
const accessToken = new AccessToken({
apiKey: "YOUR_API_KEY",
roomId: "YOUR_ROOM_ID",
role: Role.HOST,
permissions: {
admin: true,
canConsume: true,
canProduce: true,
canProduceSources: {
cam: true,
mic: true,
screen: true,
},
canRecvData: true,
canSendData: true,
canUpdateMetadata: true,
},
options: {
metadata: {
walletAddress: "manice.eth",
},
},
});
const token = accessToken.toJwt();
Note: Use Server SDK on the server side only, don’t use it on the client side.
If you want to create your custom webhook, reach out to Huddle01’s Team.
Quick Integrations
Iframe:
If you are looking to integrate Huddle01’s video conferencing features into your website without extensive coding, Huddle01's iFrame offers the perfect solution.
Using VanillaJS:
<script src="https://unpkg.com/@huddle01/iframe@0.0.11/dist/huddle01-iframe.umd.min.js"></script>
<iframe
id="huddle01-iframe"
src="https://iframe.huddle01.com/some-room"
name="myiFrame"
scrolling="no"
height="90%"
width="90%"
allowFullScreen
allow="camera; microphone; clipboard-read; clipboard-write; display-capture"
></iframe>
Using ReactJS:
npm install @huddle01/iframe
Now import the HuddleIframe
component:
import { HuddleIframe } from "@huddle01/iframe";
function App() {
return (
<div>
<HuddleIframe roomUrl="https://iframe.huddle01.com/YOUR_ROOM_ID" className="w-full aspect-video" />
</div>
);
}
CLI Tool:
The CLI tool allows you to effortlessly clone example applications for Next.js, React, Vanilla JS, and even provides a sample iframe implementation for your convenience.
Enter the following command and follow the steps:
npx huddle01-cli create
Building a Video Conferencing Room with Screen Sharing
In this tutorial, we’ll create a real-time video conferencing room where users can share their video, audio, and screen with other users in the room. Access to the room will be restricted to users with a valid roomID
.
Note: We’ll focus on implementing the SDK rather than the UI. Also, ensure that you set the required environment variables in your
.env.local
file.
Step 1: Create a Next.js App
First, run the following command and choose the relevant options to create a Next.js application:
npx create-next-app@latest your_app_name
Now, navigate to the project folder and install the required dependencies:
npm i @huddle01/react @huddle01/server-sdk
Step 2: Wrap Your App with HuddleClient
After successful installation, wrap your app with the HuddleClient
in the layout.tsx
file. Here’s how it should look:
"use client";
import React from "react";
import { HuddleClient, HuddleProvider } from "@huddle01/react";
import "./globals.css";
export default function RootLayout({ children }: { children: React.ReactNode }) {
const huddleClient = new HuddleClient({
projectId: process.env.NEXT_PUBLIC_PROJECT_ID!,
});
return (
<html lang="en">
<body>
<HuddleProvider client={huddleClient}>{children}</HuddleProvider>
</body>
</html>
);
}
Step 3: Create a Room
To allow users to join a room and share its ID, we need to call the Create Room API. Create an actions
folder in the root directory and a createRoom.ts
file. Add the following code:
"use server";
export const createRoom = async () => {
const response = await fetch("https://api.huddle01.com/api/v1/create-room", {
method: "POST",
body: JSON.stringify({
title: "Huddle01 Room",
}),
headers: {
"Content-type": "application/json",
"x-api-key": process.env.API_KEY!,
},
cache: "no-cache",
});
const data = await response.json();
const roomId = data.data.roomId;
return roomId;
};
Step 4: Generate an Access Token
We’ll generate an access token to ensure that only authorized users can join the room. Create an api/token/route.ts
file and add the following code:
import { AccessToken, Role } from "@huddle01/server-sdk/auth";
export const dynamic = "force-dynamic";
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const roomId = searchParams.get("roomId");
const role = searchParams.get("role");
if (!roomId) {
return new Response("Missing roomId", { status: 400 });
}
const accessToken = new AccessToken({
apiKey: process.env.API_KEY!,
roomId: roomId as string,
role: role as Role,
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 new Response(token, { status: 200 });
}
Now, create a file called getAccessToken.ts
under the actions
folder to call this route:
"use server";
import { Role } from "@huddle01/server-sdk/auth";
export const getAccessToken = async ({ roomId, role }: { roomId: string; role: Role }) => {
const response = await fetch(`http://localhost:3000/api/token?roomId=${roomId}&role=${role}`);
const token = await response.text();
return token;
};
Step 5: Display Peers
We’ll display the peers joining the room and their video/screen share. Create a components/ShowPeers.tsx
file and add the following code:
import React, { useEffect, useRef } from "react";
import { useRemoteAudio, useRemoteScreenShare, useRemoteVideo } from "@huddle01/react/hooks";
type Props = { peerId: string };
const ShowPeers = ({ peerId }: Props) => {
const { stream, state } = useRemoteVideo({ peerId });
const { stream: audioStream, state: audioState } = useRemoteAudio({ peerId });
const { videoStream: screenVideo, audioStream: screenAudio } = useRemoteScreenShare({ peerId });
const vidRef = useRef<HTMLVideoElement>(null);
const audioRef = useRef<HTMLAudioElement>(null);
const screenVideoRef = useRef<HTMLVideoElement>(null);
const screenAudioRef = useRef<HTMLAudioElement>(null);
useEffect(() => {
if (stream && vidRef.current && state === "playable") {
vidRef.current.srcObject = stream;
vidRef.current.play().catch(console.error);
}
}, [stream, state]);
useEffect(() => {
if (screenVideo && screenVideoRef.current) {
screenVideoRef.current.srcObject = screenVideo;
screenVideoRef.current.play().catch(console.error);
}
}, [screenVideo]);
useEffect(() => {
if (screenAudio && screenAudioRef.current) {
screenAudioRef.current.srcObject = screenAudio;
screenAudioRef.current.play().catch(console.error);
}
}, [screenAudio]);
useEffect(() => {
if (audioStream && audioRef.current && audioState === "playable") {
audioRef.current.srcObject = audioStream;
audioRef.current.play().catch(console.error);
}
}, [audioStream, audioState]);
return (
<div className="flex flex-col gap-2 size-80">
<video ref={vidRef} autoPlay muted className="border-2 rounded-xl border-white-400 aspect-video" />
{screenVideo && <video ref={screenVideoRef} autoPlay muted className="border-2 rounded-xl border-white-400 aspect-video" />}
<audio ref={audioRef} autoPlay></audio>
{screenAudio && <audio ref={screenAudioRef} autoPlay></audio>}
</div>
);
};
export default React.memo(ShowPeers);
Step 6: Main Page Implementation
Finally, we’ll integrate everything into the main page.tsx
file:
"use client";
import { useEffect, useRef, useState } from "react";
import {
useRoom,
useLocalScreenShare,
useLocalVideo,
usePeerIds,
useLocalAudio,
} from "@huddle01/react/hooks";
import { Role } from "@huddle01/server-sdk/auth";
import ShowPeers from "@/components/ShowPeers";
import { createRoom } from "@/actions/createRoom";
import { getAccessToken } from "@/actions/getAccessToken";
const Page = () => {
const [roomId, setRoomId] = useState("");
const videoRef = useRef<HTMLVideoElement>(null);
const screenRef = useRef<HTMLVideoElement>(null);
const { joinRoom, leaveRoom } = useRoom({
onJoin: () => {
console.log("Joined the room");
},
onLeave: () => {
setRoomId("");
console.log("Left the room");
},
onPeerJoin: (peer) => {
console.log("peer joined: ", peer);
},
});
const { stream, enableVideo, disableVideo, isVideoOn } = useLocalVideo();
const { enableAudio, disableAudio, isAudioOn } = useLocalAudio();
const { startScreenShare, stopScreenShare, shareStream } =
useLocalScreenShare();
const { peerIds } = usePeerIds();
useEffect(() => {
if (stream && videoRef.current) {
videoRef.current.srcObject = stream;
}
}, [stream]);
useEffect(() => {
if (shareStream && screenRef.current) {
screenRef.current.srcObject = shareStream;
}
}, [shareStream]);
const getRoomId = async () => {
const roomIdentifier = await createRoom();
setRoomId(roomIdentifier as string);
};
const getAccessTokenData = async ({
roomId,
role,
}: {
roomId: string;
role: Role;
}) => {
const tokenData = await getAccessToken({ roomId, role });
return tokenData;
};
return (
<div className="flex items-center justify-center mt-10">
<div className="flex flex-col w-1/4 items-center space-y-6 mx-10">
<input
onChange={(e) => {
setRoomId(e.target.value);
}}
value={roomId}
className="text-black mx-auto w-[300px] rounded-md p-2"
/>
<div className="flex space-x-4 items-center">
<button
onClick={getRoomId}
type="button"
className="bg-blue-500 p-2 rounded-md"
>
Get room id
</button>
<div className="bg-red-100 w-52 rounded-md">
<p className="text-center text-black p-2">Room id: {roomId}</p>
</div>
</div>
<div className="flex space-x-4 items-center">
<button
onClick={async () => {
const tokenData = await getAccessTokenData({
roomId,
role: Role.HOST,
});
joinRoom({
roomId: roomId,
token: tokenData,
});
console.log("Joined as Host");
}}
type="button"
className="bg-blue-500 p-2 rounded-md"
>
Join as Host
</button>
<button
onClick={async () => {
const tokenData = await getAccessTokenData({
roomId,
role: Role.GUEST,
});
joinRoom({
roomId: roomId,
token: tokenData,
});
}}
type="button"
className="bg-blue-500 p-2 rounded-md"
>
Join as Guest
</button>
</div>
<div className="flex space-x-4">
<button
type="button"
className="bg-blue-500 p-2 rounded-lg"
onClick={async () => {
isAudioOn ? await disableAudio() : await enableAudio();
}}
>
{isAudioOn ? "Disable" : "Enable"} Audio
</button>
<button
type="button"
className="bg-blue-500 p-2 rounded-md"
onClick={() => {
isVideoOn ? disableVideo() : enableVideo();
}}
>
Video {isVideoOn ? "Off" : "On"}
</button>
<button
type="button"
className="bg-blue-500 p-2 rounded-md"
onClick={() => {
shareStream ? stopScreenShare() : startScreenShare();
}}
>
Screen Share {shareStream ? "Off" : "On"}
</button>
</div>
<button
onClick={leaveRoom}
type="button"
className="bg-red-500 p-2 rounded-md"
>
Leave Room
</button>
</div>
<div className="w-full flex gap-4 justify-between items-stretch">
<div className="flex-1 justify-between items-center flex flex-col">
<div className="relative flex place-items-center before:absolute before:size-80 before:-translate-x-1/2 before:content-[''] after:absolute after:-z-20 after:h-[180px] after:w-[240px] after:translate-x-1/3 after:content-[''] before:lg:h-[360px]">
<div className="relative flex gap-2">
{isVideoOn ? (
<div className="w-1/2 mx-auto border-2 rounded-xl border-blue-400">
<video
ref={videoRef}
className="aspect-video rounded-xl"
autoPlay
muted
/>
</div>
) : (
<div className="size-[300px] flex items-center justify-center mx-auto border-2 rounded-xl border-blue-400">
No videos turned on
</div>
)}
{shareStream && (
<div className="w-1/2 mx-auto border-2 rounded-xl border-blue-400">
<video
ref={screenRef}
className="aspect-video rounded-xl"
autoPlay
muted
/>
</div>
)}
</div>
</div>
<div className="mt-4 mb-10 grid gap-2 text-center">
{peerIds.map((peerId) =>
peerId ? <ShowPeers key={peerId} peerId={peerId} /> : null
)}
</div>
</div>
</div>
</div>
);
};
export default Page;
Step 7: Run the Application
Run the following command to start the application:
npm run dev
Other Resources :
Some Potential Tool/Project Ideas
Here are some ideas for tools/products that can be built leveraging the Huddle01 SDK:
Decentralized Virtual Events Platform: Make a platform where people can organize and join virtual events like conferences, workshops, or meetups using the Huddle01 SDK. This platform could include features like customizable event spaces, virtual networking chances, and interactive presentations, all using Huddle01's dRTC Protocol. It would address the need for secure and scalable virtual event solutions in the market.
Decentralized Online Education Platform: Create an online education platform that links students with tutors and instructors for interactive lessons and tutoring sessions. Using the Huddle01 SDK, this platform could offer real-time audio and video communication, whiteboarding tools, and secure payment processing. By decentralizing the platform, it would empower educators and learners while maintaining privacy and security.
Secure Telehealth Application: Create a telehealth app enabling patients to connect with healthcare providers for virtual consultations. Using the Huddle01 SDK, this app could provide HIPAA-compliant video calls, secure messaging, and file sharing. By decentralizing the infrastructure, it would boost patient privacy and data security, addressing a key need in the telehealth industry.
Blockchain-Based Social Networking Platform: Develop a decentralized social networking platform where users can connect and interact while keeping control over their data and privacy. With the Huddle01 SDK, this platform could provide secure messaging, group video chats, and content sharing. By incorporating blockchain technology, it would allow clear governance and encourage community involvement, bringing new features to social networking.
Conclusion
So, yeah we are at the end of this long article, throughout the article we have explored the amazing features and ease-of-use ecosystem of Huddle01. I hope I was able to deliver the pinpoint and truthful information to my readers.
Huddle01 is indeed an awesome project whose journey began with a vision at the ETHGlobal Hackathon in 2019: to revolutionize communication by placing power back in the hands of the people. Rather than having conversations controlled and monitored by centralized entities, Huddle01 aimed to build a decentralized network where individuals govern their communication. In just two short years, they've scaled immensely, introducing their very own Video Meeting dApp, an advanced Communication Infrastructure, and most importantly, the groundbreaking dRTC Network.
To the till date 200+ projects have been developed with Huddle01's SDKs addressing various solutions worldwide. I encourage you, as a potential developer, to consider using Huddle01 for your next project.
Thank you for reaching this end.
To get more information about Huddle01 dApp or Huddle01 ecosystem you can refer to these 2 videos :
Subscribe to my newsletter
Read articles from Soumyodeep Das directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by