Skip to main content
Version: 2.x.x

Initialize Live Stream - React Native

To configure livestreaming with VideoSDK, you need two things: a token for Authentication, and a streamId that specifies where the hosts and audience join.

Generating Token​

You can generate a token in two ways:

  1. Temporary Token : You can visit Dashboard's API Key section and generate a temporary token from there.

  2. Server : You can set up JWT in your backend and make an API call to get the token from your server.

To learn more about Authentication and token in detail you can follow this guide.

With a temporary token:

const getToken = async () => {
// Update the token here from the VideoSDK dashboard
let token = "YOUR_TOKEN";
return token;
};

With a token from your server:

const getToken = async () => {
const response = await fetch(`http://localhost:3000/get-token`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
});
const { token } = await response.json();
return token;
};

Generating Stream Id​

With the token ready, you can now get the streamId from the VideoSDK's rooms API.

const getStreamId = async (token) => {
try {
//Use VideoSDK rooms API endpoint to create a streamId
const VIDEOSDK_API_ENDPOINT = `https://api.videosdk.live/v2/rooms`;
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
// Pass the token in the headers
Authorization: token,
},
};
const streamId = await fetch(VIDEOSDK_API_ENDPOINT, options)
.then(async (result) => {
const { roomId } = await result.json();
return roomId;
})
.catch((error) => console.log("error", error));

//Return the streamId received from the response of the api
return streamId;
} catch (e) {
console.log(e);
}
};

Initialization of Live Stream​

You can initialize the live stream using the RoomProvider from the React Native SDK. The RoomProvider is responsible for initializing the live stream with the provided configuration, which includes the token, roomId, participantId and many more.

Room Provider​

RoomProvider is React's Context.Provider that lets the components inside it subscribe to changes in the live stream. You have to pass the initialization configuration for the live stream and the token in the RoomProvider.

RoomProvider leaves the room when it unmounts. Keep it mounted for as long as the call lasts.

<RoomProvider
config={{
roomId: "<streamId>",
mode: "SEND_AND_RECV", // "SEND_AND_RECV" for hosts/co-hosts, "RECV_ONLY" for audience
participantName: "<Participant Name>",
micEnabled: true, // Ignored for audience
camEnabled: true, // Ignored for audience
participantId: "<Unique Participant ID>", // Optional
multiStream: true, // Optional, default: true. Ignored for audience
}}
token={"token"}
joinWithoutUserInteraction={false} // true = join automatically; if true, do not call join()
>
<StreamView />
</RoomProvider>
  • roomId :

    • This is a unique identifier that allows participants to join a specific live stream.
    • It will be in the format of xxx-yyy-zzz and will be generated using the VideoSDK's Room API.
  • mode :

    • This parameter defines the mode the participant will enter the live stream with.
    • SEND_AND_RECV: For hosts/co-hosts who can send and receive media.
    • RECV_ONLY: For audience members who can only receive media.
  • participantName:

    • This represents the name of the participant in the live streams.
    • It will accept String type value.
    • This is an OPTIONAL parameter. By default, VideoSDK picks a random 6-character name.
  • micEnabled:

    • This is an optional boolean flag, true by default, indicating whether a participant's microphone will be automatically enabled when they join the live stream. This property will be completely ignored for Audience participants, as they are not allowed to publish their audio.
  • camEnabled:

    • This is an optional boolean flag, true by default, indicating whether a participant's webcam will be automatically enabled when they join the live stream. This property will be completely ignored for Audience participants, as they are not allowed to publish their video.
  • metaData:

    • If you want to provide additional details about the participants joining the live stream, such as their profile image, you can pass that information in this parameter.
    • It has to be of Object type.
    • This is an OPTIONAL parameter.
  • participantId:

    • This is a unique identifier for the participant inside the live stream.

      • It can be used to specify the unique identifier which can be linked with your own database service.
      • It has to be of String type.
      • This is an OPTIONAL parameter. By default, VideoSDK generates a unique id for each participant.
  • multiStream:

    • This is a boolean flag, indicating whether the camera that VideoSDK opens for the host sends multiple resolution layers or a single resolution layer.
    • This is an OPTIONAL parameter. By default, it is true.
  • defaultCamera:

    • This is an OPTIONAL parameter, It sets the initial camera configuration.
    • It accepts two distinct values : front or back.
    • By default, it's value is set to front.
  • autoConsume:

    • This is an OPTIONAL boolean flag. By default, it is true: the participant receives the audio and video of every remote participant.
    • With false, remote media arrives unsubscribed. See Choose which media to receive.
note

On Android, the SDK does not ask the user for camera and microphone access. Request access before a host joins, as shown in Join Live Stream. Without it, the camera and microphone do not start, even when camEnabled and micEnabled are true.

caution

You must ensure that the participantId is not repeated in the same livestream. This will enable VideoSDK to eliminate any participant associated with that participantId.

Other Options for Room Provider​
  • joinWithoutUserInteraction:

    • true — The participant joins the livestream automatically. Do not call join() manually.

    • false (default) — The participant does not join automatically. Your code must call join().

    • Use only one join mechanism. If you use join(), do not enable joinWithoutUserInteraction.

To know more about other properties, you can follow our API Reference.

Choose which media to receive​

With autoConsume: false, a participant receives no remote audio or video until they ask for it. This suits an audience member who watches one host at a time.

<RoomProvider
config={{
roomId: "<streamId>",
mode: "RECV_ONLY",
autoConsume: false, // Receive nothing until you ask for it
}}
token={"token"}
>
<StreamView />
</RoomProvider>

Then call consumeWebcamStreams() and consumeMicStreams() from useParticipant to start receiving one participant's video and audio. stopConsumingWebcamStreams() and stopConsumingMicStreams() stop it again. Each method returns a Promise.

function HostView({ participantId }) {
const {
consumeWebcamStreams,
consumeMicStreams,
stopConsumingWebcamStreams,
stopConsumingMicStreams,
} = useParticipant(participantId);

const watch = async () => {
try {
await consumeWebcamStreams();
await consumeMicStreams();
} catch (error) {
console.error("Failed to receive the host's media", error);
}
};

const stopWatching = async () => {
try {
await stopConsumingWebcamStreams();
await stopConsumingMicStreams();
} catch (error) {
console.error("Failed to stop receiving the host's media", error);
}
};

return (
<View>
<TouchableOpacity onPress={watch}>
<Text>Watch</Text>
</TouchableOpacity>
<TouchableOpacity onPress={stopWatching}>
<Text>Stop watching</Text>
</TouchableOpacity>
</View>
);
}

With all the configuration options explained, here is how you will use the RoomProvider.

// imports
import { RoomProvider, useRoom } from "@videosdk.live/react-native-sdk";
import { View, Text } from "react-native";
import { useState, useEffect } from "react";

const getToken = async () => {
// ...
};
const getStreamId = async (token) => {
// ...
};

// isHost comes from your join screen
const App = ({ isHost }) => {
const [streamId, setStreamId] = useState(null);
const [token, setToken] = useState(null);

const fetchStreamIdandToken = async () => {
//Fetch the token and streamId and update it in the state
const newToken = await getToken();
const newStreamId = await getStreamId(newToken);
setToken(newToken);
setStreamId(newStreamId);
};

useEffect(() => {
//Load the token and generate a streamId and pass it to the RoomProvider
fetchStreamIdandToken();
}, []);

// Init RoomProvider
return token && streamId ? (
<RoomProvider
config={{
// Pass the generated streamId
roomId: streamId,
participantName: "NAME HERE",
micEnabled: true,
camEnabled: true,
// If a participant joins as a host, use the mode "SEND_AND_RECV".
// Otherwise, use the "RECV_ONLY" mode.
mode: isHost ? "SEND_AND_RECV" : "RECV_ONLY",
}}
// Pass the generated token
token={token}
// Joins automatically. On Android, request camera and microphone access for hosts before this renders.
joinWithoutUserInteraction={true}
>
<StreamView />
</RoomProvider>
) : (
<View />
);
};

const StreamView = () => {
// Get stream object using useRoom hook
const stream = useRoom();
console.log("Stream Obj", stream);

return <View />;
};

export default App;

React Hooks Support​

VideoSDK's React Native SDK provides hooks which can be used to access the state of the livestream and listen to the events happening in the livestream.

caution

All the hooks mentioned below are accessible within the RoomProvider only.

useRoom​

The useRoom hook gives you the live stream's state and events, such as a participant joining or leaving. To know more about the properties and events accessible by this hook, go through our API Reference.

useParticipant​

The useParticipant hook gives you one participant's state and events, such as their webcam and mic status. To know more about the properties and events accessible by this hook, go through our API Reference.

usePubSub​

The usePubSub hook sends and receives messages between the participants in the live stream. It can be used to develop features like Chat, Raise Hand etc. To know more about the usePubSub hook, take a look at detailed explanation of publish-subscribe mechanism.

API Reference​

The API references for all the methods utilized in this guide are provided below.

Got a Question? Ask us on discord