Back to Blog

Migration Guide from Twilio to Agora: Web Edition

Migration Guide from Twilio to Agora: Web Edition

We're offering up to 2 free months to any customer switching from Twilio video to Agora. Schedule some time to chat with our team to get the full details.


Introduction

This guide will assist you in migrating your existing Twilio Video implementation to the Agora Video SDK. If you are initiating a new project, it is advised to refer to the Agora Video SDK documentation.

Quickstart

Quickstart demos for React, Vue, and Svelte are provided. Check them out at Quickstart Demo. Additional demos can be found ar More Demos.

Please follow the documentation here: Video Calling SDK quickstart - Web.

Creating an Account with Agora

Sign up for an account and log in to the Agora Console.

Agora React SDK: Build a video conferencing app in minutes - Signup
The project management tab on the Agora website

Navigate to the Project List tab under the Project Management tab, and create a project by clicking the blue Create button. (When prompted to use App ID + Certificate, select App ID only.) Retrieve the App ID, which will be used to authorize your requests while you’re developing the application.

Note: This guide does not implement token authentication, which is recommended for all RTE apps running in production environments. For more information about token-based authentication in the Agora platform, see this guide: https://docs.agora.io/en/video-calling/get-started/authentication-workflow?platform=web

Step 1: Obtain Agora Video SDK Keys

To access Agora services and integrate them into your project, follow these steps to obtain the necessary information from the Agora Console:

App ID

  1. Log in to the Agora Console and navigate to your project.
  2. Find the “App ID,” a randomly generated string unique to your App. This ID is crucial for identifying your application within Agora.

Temporary Token

  • When clients from your App join a channel, they need a Token for authentication.
  • Generate a temporary Token from the Agora Console, which has a validity period of 24 hours. This Token is used to authenticate users joining your channel.

Channel Name

  • Define a unique string as the “Channel Name” to identify and label your channel.

By completing these steps, you’ll have the necessary credentials to integrate Agora services into your application. Refer to the Agora Console for detailed guidance on accessing and managing these credentials.

Step 2: Install Agora Video SDK

Install

Use npmpnpm, or yarn

# with npm
npm i agora-rtc-sdk-ng
# or with pnpm
pnpm add agora-rtc-sdk-ng
# or with yarn
yarn add agora-rtc-sdk-ng
view raw bash.sh hosted with ❤ by GitHub

Or, use Agora Video SDK CDN script tag:

<script src="https://download.agora.io/sdk/release/AgoraRTC_N-4.20.0.js"></script>
view raw main.html hosted with ❤ by GitHub

Remove Twilio SDK from your project:

If using npm:

npm uninstall twilio-video

If using Twilio CDN:

Remove the Twilio script tag from index.html.

Proceed to the next step for configuration details.

Step 3: Start and Join Sessions

Twilio

// Replace Twilio Video import
import * as TwilioVideo from 'twilio-video'
var twilioVideo = TwilioVideo
var twilioRoom
twilioRoom = await twilioVideo.connect(TOKEN, { name: 'yourName', audio: false, video: false, dominantSpeaker: true })
view raw main.ts hosted with ❤ by GitHub

Agora

// Initialize Agora Client
const client = AgoraRTC.createClient({
codec: "vp8",
mode: "rtc",
});
// join room
await client.join("APPID", "CHANNEL", "TOKEN", 393939);
view raw main.ts hosted with ❤ by GitHub

Step 4: Create Local Audio and Video Tracks and Publish

<div class="video-container-div" width="1920" height="1080"></div>
view raw main.ts hosted with ❤ by GitHub

Twilio

// video
let localVideoTrack = await twilioVideo.createLocalVideoTrack({
height: { ideal: 720, min: 480, max: 1080 },
width: { ideal: 1280, min: 640, max: 1920 },
aspectRatio: 16/9,
})
twilioRoom.localParticipant.publishTrack(localVideoTrack)
const localMediaContainer = document.getElementById('video-container-div')
localMediaContainer!.appendChild(localVideoTrack.attach())
// audio
let localAudioTrack = await twilioVideo.createLocalAudioTrack()
twilioRoom.localParticipant.publishTrack(localAudioTrack);
const audioElement = localAudioTrack.attach();
document.body.appendChild(audioElement);
view raw main.ts hosted with ❤ by GitHub

Agora

createMicrophoneAndCameraTracks:Create a local track using the audio and video captured by the microphone and camera at the same time, and return a list containing CameraVideoTrack and MicrophoneAudioTrack

// Capture both microphone and camera
const [microphoneTrack, cameraTrack] = await AgoraRTC.createMicrophoneAndCameraTracks();
// Rendering option 1
const localMediaContainer = document.getElementById('video-container-div')
cameraTrack.play(localMediaContainer);
// Rendering option 2
cameraTrack.play("agora-self-view-div");
// Publish camera tracks
await client.publish([microphoneTrack, cameraTrack]);
view raw main.ts hosted with ❤ by GitHub

Step 5: Unpublish and Destroy Tracks

  1. Turn the Camera/Microphone Off in Twilio
    Twilio Video/Audio is track-based, requiring looping through each video/audio track to unpublish the video/audio.
twilioRoom.localParticipant.videoTracks.forEach((publication) => {
publication.unpublish();
publication.track.stop();
var selfTwilioVideo = document.getElementById('video-container-div')
selfTwilioVideo?.querySelector('video')?.remove()
})
twilioRoom.localParticipant.audioTracks.forEach((publication) => {
publication.track.disable()
})
view raw main.ts hosted with ❤ by GitHub
  1. Unpublish Video/Audio
// Publish audio and video
await client.publish([localAudioTrack, localVideoTrack]);
// Unpublish video, audio remains published
await client.unpublish(localVideoTrack);
// Unpublish all tracks at once
await client.unpublish();
// Or, unpublish a specific set of tracks
await client.unpublish([localAudioTrack, localVideoTrack]);
view raw main.ts hosted with ❤ by GitHub

​ Note on unpublish:

  • This method can be called multiple times. You can use publish and unpublish to manage the publication and unpublishing of specific local tracks.
  • This method is asynchronous and should be used with Promise or async/await.

Track destruction:

localAudioTrack.close();
localVideoTrack.close();
view raw main.ts hosted with ❤ by GitHub

Step 6: Render Remote User Video

<div class="remote-video-container-div" width="1920" height="1080"></div>
view raw main.ts hosted with ❤ by GitHub
  1. Rendering Remote User Video in Twilio
    In Twilio, you might have used `participantConnected` and `trackSubscribed` event listeners.
twilioRoom.on('participantConnected', (participant) => {
participant.on('trackSubscribed', (track) => {
// a user turned on their video, render it
document.getElementById('remote-video-container-div').appendChild(track.attach());
});
participant.on('trackUnsubscribed', (track) => {
// a user turned off their video, stop rendering it
var selfTwilioVideo = document.getElementById('remote-video-container-div')
selfTwilioVideo.querySelector('video').remove()
})
})
view raw main.ts hosted with ❤ by GitHub
  1. Rendering Remote User Video in Agora
    Once a remote user successfully publishes audio/video tracks, the SDK triggers the user-published event. This event carries two parameters: the remote user object ( user) and the media type published remotely ( mediaType). At this point, you can use AgoraRTCClient.subscribe to initiate subscription.
client.on("user-published", async (user, mediaType) => {
// Initiate a subscription
await client.subscribe(user, mediaType);
// Subscribe to an audio track
if (mediaType === "video") {
const audioTrack = user.audioTrack;
// Automatically play audio
audioTrack.play();
} else {
const videoTrack = user.videoTrack;
// Automatic video playback
videoTrack.play('remote-video-container-div');
}
});
view raw main.ts hosted with ❤ by GitHub

After the subscription method completes, you can retrieve the corresponding RemoteAudioTrack and RemoteVideoTrack objects using user.audioTrack and user.videoTrack.

Subscription and publication differ, allowing you to subscribe to only one audio or video track at a time. Even if the publishing side simultaneously publishes both audio and video tracks, the SDK triggers the user-published event twice: once for user-published(audio) and once for user-published(video). Following the code logic above, it completes two subscriptions.

Step 7: Leave and End Sessions

Twilio to Agora Migration Code Changes

  1. Leaving a Session in Twilio
    In Twilio, you might have used the disconnect function to leave a session.

    twilioVideo.disconnect()
  1. Leaving a Session in Agora
    After calling leave, the SDK immediately destroys objects related to the current channel, including subscribed remote user objects, remote track objects, and objects recording connection status. If you need to rejoin the channel, call join after calling leave.

Additional Agora Video SDK Features

The Agora Video SDK provides a rich set of features that can enhance your video conferencing application. Here are some key features and information to consider:

  1. Platform Support:
    Agora Video SDK supports a variety of platforms, including Android, iOS, Web, Linux, macOS, and Windows. Additionally, it offers wrappers for popular frameworks like Flutter and React Native.
  2. Cloud Recording:
    Agora Video SDK provides cloud recording capabilities, allowing you to capture and store your sessions for later playback or archival purposes. Consult the Agora Video SDK documentation for details on implementing this feature.
  3. Screen Sharing:
    Implement screen sharing in your application using Agora’s screen-sharing capabilities. This feature is valuable for collaborative work and presentations.
  4. Plug-in Architecture:
    Agora’s support for plug-ins enhances the extensibility of your video application. You can seamlessly integrate additional functionalities or customize features by leveraging Agora’s plug-in architecture.
  5. Tree-Shaking:
    Agora Video SDK supports tree-shaking, enabling you to optimize your application’s bundle size by eliminating unused code during the build process. This ensures that your application remains lightweight and performs efficiently.
  6. Secure Communication:
    Agora’s end-to-end encryption ensures that the communication between users in a session is highly secure. This feature enhances privacy and protects sensitive information exchanged during video conferences.

For comprehensive details on Agora Video SDK features and how to implement them, refer to the Agora Video SDK Documentation.

Explore the full potential of Agora Video SDK to create a robust and feature-rich video conferencing experience. If you have specific feature requirements, consult the documentation for guidance on implementation.

RTE Telehealth 2023
Join us for RTE Telehealth - a virtual webinar where we’ll explore how AI and AR/VR technologies are shaping the future of healthcare delivery.

Learn more about Agora's video and voice solutions

Ready to chat through your real-time video and voice needs? We're here to help! Current Twilio customers get up to 2 months FREE.

Complete the form, and one of our experts will be in touch.

Try Agora for Free

Sign up and start building! You don’t pay until you scale.
Try for Free