Twilio Programmable Video Migration Guide

Twilio Programmable Video is a WebRTC-based API for quickly adding real-time communication capabilities to your mobile and web applications.
connect(token, { name }), you create the call with client.call(type, id) and join it with call.join(). Local tracks are replaced by call.camera and call.microphone, and room status callbacks become call webhooks.If you're evaluating alternative video APIs to meet the needs of your applications, a solution like Stream can help.
In this blog post, we will take a look at Stream Video and the steps developers can take to quickly add real-time communication capabilities to their applications in just a few lines of code.
If you would like to jump directly into building with Stream Video, you can skip ahead to Building with Stream.
Why Migrate to Stream Video?
Stream Video is a robust WebRTC-based Video API that offers high-quality video calling, audio rooms, and livestreaming directly out of the box. Stream is built for scale and reliability, supporting SFU cascading and global nodes via our global edge network to ensure our customers always have the lowest latency while on calls.
With Stream's unique architecture and design, our API is able to effectively scale to large groups, automatically handle and resolve video codecs, and make resolution adjustments based on the user's device state and connection speed.
Developers building with Stream can benefit from our rich set of UI components and SDKs across all significant technology stacks and platforms. Our UI Components are very powerful and customizable, allowing developers and businesses to quickly integrate real-time experience in just a few lines of code. Stream's Video API is available with SDKs for React, React Native, Flutter, Android, iOS, JavaScript, Unity, and ESP32.
Pricing is usage-based and published on our pricing page. Audio for video calls starts at $0.30 per 1,000 participant minutes, and your first $100 of usage is free each month on every plan.
To learn more about the full list of features Stream supports, please check out our Video product page.
Twilio to Stream Concept Map
Most Twilio Video concepts have a direct counterpart in Stream:
| Twilio Video | Stream Video |
|---|---|
| Access token with a Video grant | User token, generated by Stream's server SDK |
| Room | Call, created with client.call(type, id) |
| Participant | Participant, available in the call state |
| LocalTrack | call.camera, call.microphone and screen share. Defaults come from the call type (camera_default_on, mic_default_on) |
| RemoteTrack | Participant state, which holds each participant's audio and video streams |
participantConnected / participantDisconnected |
call.session_participant_joined / call.session_participant_left events |
| Screen share track | call.screenShare |
| DataTrack | Custom events, for signalling only, with a 5KB payload limit |
| Network Quality API | Each participant's connectionQuality, plus detailed call stats |
| Recordings and Compositions | Composite or individual-track recording |
| Room status callbacks | Call webhooks |
Building with Stream
Call and most objects on Stream allow for custom data to add attributes such as name or image URLs, etc.
When you're ready to dive into the code, you can obtain your free API key by visiting our website and creating a free account.
Once your account is created, you will be taken to the Stream Dashboard, where you will be able to copy or create an API key for your project.

The Stream dashboard also allows you to quickly create and test different call types, such as livestreaming or audio rooms without having to open a second instance of your application locally.
With the setup complete, we can now take a look at what it takes to build a simple calling application in Javascript. If you want to skip ahead to a complete working app, follow the React video calling tutorial.
Project Setup
In this example, we will use Stream's React SDK as our testing framework, but Stream Video is available across all major frameworks and platforms. The steps for getting started with Stream are similar across all of our SDKs, so if React/Javascript is not your first choice, please feel free to follow along using one of the others:
yarn create vite video-call --template react-ts
cd video-call
yarn add @stream-io/video-react-sdkNext, we can open the src/App.tsx file and replace all of the code in this file with the import to the Stream library as well as declare our API keys for use later in the project.
import {
CallingState,
StreamCall,
StreamVideo,
StreamVideoClient,
useCall,
useCallStateHooks,
User,
} from "@stream-io/video-react-sdk";
const apiKey = "REPLACE_WITH_API_KEY"; // the API key can be found in the project Dashboard
const token = "REPLACE_WITH_TOKEN"; // the token can be generated using the Project's Secret and our online generator
const userId = "REPLACE_WITH_USER_ID"; // the ID of the user you generated the token for
const callId = "REPLACE_WITH_CALL_ID"; // any string you choose; everyone who uses it joins the same callNote : To quickly generate a user token while developing, you can use our online token generator. For production applications, it is strongly recommended that tokens are only generated on your application's backend.
To connect to the Stream API, we need to define a user object containing the userId, name, and image, then instantiate a new instance of the Stream client:
// set up the user object
const user: User = {
id: userId,
name: "Oliver",
image: "https://getstream.io/random_svg/?id=oliver&name=Oliver",
};
const client = new StreamVideoClient({ apiKey, user, token });
const call = client.call("default", callId);
call.join({ create: true });Stream has six built-in call types: default, the most common for conferencing apps; audio_call for voice calls; audio_room for Twitter Spaces-style audio experiences; livestream for streaming with RTMP and HLS support; agent for calls with an AI agent; and development for testing. You can also define your own call types on the dashboard.
Building the UI
With our imports and API keys defined, we can move on to the fun part of creating the UI for our application.
Stream's SDKs are developed in layers, starting with our pre-built UI components at the very top and native API wrappers at the bottom. For developers and businesses building with Stream, you can quickly add and customize components to your application that are already pre-connected to our API, reduce your development time, or build completely bespoke UIs using your own design systems and components.
export default function App() {
return (
<StreamVideo client={client}>
<StreamCall call={call}>
<MyUILayout />
</StreamCall>
</StreamVideo>
);
}
export const MyUILayout = () => {
const call = useCall();
const { useCallCallingState, useParticipantCount } = useCallStateHooks();
const callingState = useCallCallingState();
const participantCount = useParticipantCount();
if (callingState !== CallingState.JOINED) {
return <div>Loading...</div>;
}
return (
<div>
Call "{call?.id}" has {participantCount} participants
</div>
);
};In the above code snippet, we are defining the overall structure of our application in the App function by creating a new instance of StreamVideo containing the client and configuration defined earlier. Next, StreamCall is used to listen to and manage the state of our call, while MyUILayout defines the structure of our call screen.
When building custom UIs, Stream's SDKs allow for easy access to low-level states and methods of the Video SDK, such as using Hooks to listen and react to changes in the call state or number of participants in a given call easily.
To learn more about React (or any SDK), please visit our documentation hub on our website. Guides for features such as video filters, screen sharing, and custom events can be found in each SDK's docs.
Twilio vs. Stream, Step by Step
Each step below shows the Twilio code first, then the Stream equivalent. Connecting, camera and mic, rendering, and leaving are shown for Web, iOS, and Android. The other steps are shown for the web and server, since they work the same way across Stream's SDKs. The Twilio snippets come from Twilio's own docs and official quickstarts, trimmed for length.
Step 1: Generate Tokens on Your Server
Twilio issues an access token with a Video grant. Stream issues a user token from its server SDK, using your API key and secret.
Twilio (Node.js)
const AccessToken = require("twilio").jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;
function createToken(userId) {
const token = new AccessToken(twilioAccountSid, twilioApiKey, twilioApiSecret, {
identity: userId,
});
token.addGrant(new VideoGrant({ room: "my-room-name" }));
return token.toJwt();
}Stream (Node.js)
import { StreamClient } from "@stream-io/node-sdk";
const client = new StreamClient(apiKey, secret);
function createToken(userId) {
// Tokens are valid for an hour by default
return client.generateUserToken({ user_id: userId, validity_in_seconds: 60 * 60 });
}Step 2: Connect to a Room (Join a Call)
Twilio (Web)
import { connect, createLocalTracks } from "twilio-video";
const localTracks = await createLocalTracks({ audio: true, video: { width: 640 } });
const room = await connect(token, { name: "my-room-name", tracks: localTracks });Stream (Web)
import { StreamVideoClient } from "@stream-io/video-client";
const client = new StreamVideoClient({ apiKey, token, user });
const call = client.call("default", "my-room-name");
await call.join({ create: true });Twilio (iOS)
import TwilioVideo
// camera is a CameraSource set up for the front camera
let localAudioTrack = LocalAudioTrack(options: nil, enabled: true, name: "Microphone")
let localVideoTrack = LocalVideoTrack(source: camera, enabled: true, name: "camera")
let connectOptions = ConnectOptions(token: accessToken) { builder in
builder.roomName = "my-room-name"
builder.audioTracks = [localAudioTrack!]
builder.videoTracks = [localVideoTrack!]
}
room = TwilioVideoSDK.connect(options: connectOptions, delegate: self)Stream (iOS)
import StreamVideo
let streamVideo = StreamVideo(
apiKey: apiKey,
user: user,
token: token,
tokenProvider: { result in
// Fetch a fresh token from your backend when this one expires
}
)
let call = streamVideo.call(callType: "default", callId: "my-room-name")
try await call.join(create: true)Twilio (Android)
// cameraCapturer comes from the quickstart's CameraCapturerCompat helper
localAudioTrack = createLocalAudioTrack(this, true)
localVideoTrack = createLocalVideoTrack(this, true, cameraCapturer)
room = connect(this, accessToken, roomListener) {
roomName("my-room-name")
audioTracks(listOf(localAudioTrack))
videoTracks(listOf(localVideoTrack))
}Stream (Android)
val client = StreamVideoBuilder(
context = applicationContext,
apiKey = apiKey,
user = user,
token = userToken,
).build()
val call = client.call(type = "default", id = "my-room-name")
call.join(create = true)Step 3: Turn the Camera and Microphone On or Off
Twilio (Web)
// track.enable() turns it back on
room.localParticipant.audioTracks.forEach((publication) => {
publication.track.disable();
});
room.localParticipant.videoTracks.forEach((publication) => {
publication.track.disable();
});Stream (Web)
// enable() turns it back on
await call.microphone.disable();
await call.camera.disable();Twilio (iOS)
localAudioTrack?.isEnabled = false
localVideoTrack?.isEnabled = falseStream (iOS)
try await call.microphone.disable()
try await call.camera.disable()Twilio (Android)
localAudioTrack?.enable(false)
localVideoTrack?.enable(false)Stream (Android)
call.microphone.setEnabled(false)
call.camera.setEnabled(false)Step 4: Render Other Participants
With Twilio, you attach each remote track as it's subscribed. With Stream, you render from the call's participant state, which updates as people join, leave, and turn their camera on or off.
Twilio (Web)
room.on("participantConnected", (participant) => {
participant.on("trackSubscribed", (track) => {
document.getElementById("remote-media-div").appendChild(track.attach());
});
});Stream (Web)
// Simplified: reuse existing elements in real code
call.state.remoteParticipants$.subscribe((participants) => {
participants.forEach((participant) => {
const video = document.createElement("video");
const audio = document.createElement("audio");
document.getElementById("participants").append(video, audio);
call.bindVideoElement(video, participant.sessionId, "videoTrack");
call.bindAudioElement(audio, participant.sessionId, "audioTrack");
});
});Twilio (iOS)
func didSubscribeToVideoTrack(videoTrack: RemoteVideoTrack,
publication: RemoteVideoTrackPublication,
participant: RemoteParticipant) {
remoteView = VideoView(frame: view.bounds, delegate: self)
videoTrack.addRenderer(remoteView!)
}Stream (iOS)
let participants = call.state.remoteParticipants
// Show each participant with VideoRendererView,
// or use the built-in CallContainer for a full call screenTwilio (Android)
override fun onVideoTrackSubscribed(
remoteParticipant: RemoteParticipant,
remoteVideoTrackPublication: RemoteVideoTrackPublication,
remoteVideoTrack: RemoteVideoTrack,
) {
remoteVideoTrack.addSink(primaryVideoView)
}Stream (Android)
// Jetpack Compose
val participants by call.state.participants.collectAsState()
participants.forEach { participant ->
ParticipantVideo(call = call, participant = participant)
}Step 5: Handle Participants Joining and Leaving
Twilio (Web)
room.on("participantConnected", (participant) => {
console.log(`Participant "${participant.identity}" connected`);
});
room.on("participantDisconnected", (participant) => {
console.log(`Participant "${participant.identity}" disconnected`);
});Stream (Web)
call.on("call.session_participant_joined", (event) => {
console.log(`Participant "${event.participant.user.id}" joined`);
});
call.on("call.session_participant_left", (event) => {
console.log(`Participant "${event.participant.user.id}" left`);
});Step 6: Send Data Messages
Twilio uses a DataTrack you publish into the room. Stream uses custom events on the call, with no track to manage. Custom events are meant for signalling, with a 5KB payload limit.
Twilio (Web)
import { connect, LocalDataTrack } from "twilio-video";
const dataTrack = new LocalDataTrack();
const room = await connect(token, { name: "my-room-name", tracks: [dataTrack] });
// Send (once the track is published)
dataTrack.send(JSON.stringify({ type: "draw", x: 10, y: 30 }));
// Receive
room.on("trackSubscribed", (track) => {
if (track.kind === "data") {
track.on("message", (data) => console.log(data));
}
});Stream (Web)
// Send
await call.sendCustomEvent({ type: "draw", x: 10, y: 30 });
// Receive
call.on("custom", (event) => {
console.log(event.custom);
});Step 7: Share Your Screen
Twilio (Web)
import { LocalVideoTrack } from "twilio-video";
const stream = await navigator.mediaDevices.getDisplayMedia({ video: { frameRate: 15 } });
const screenTrack = new LocalVideoTrack(stream.getTracks()[0], { name: "myscreenshare" });
await room.localParticipant.publishTrack(screenTrack);
// Unpublish when sharing stops
screenTrack.on("stopped", () => {
room.localParticipant.unpublishTrack(screenTrack);
});Stream (Web)
await call.screenShare.enable();
// ...and to stop
await call.screenShare.disable();Step 8: Record a Call
Twilio records each track separately, then uses a Composition to combine them into one playable file. Stream's composite recording produces a single file directly, and fires call.recording_ready when it's done.
Twilio (Node.js)
const client = require("twilio")(apiKey, apiSecret, { accountSid });
// Start recording everyone in the room
await client.video.v1
.rooms(roomSid)
.recordingRules.update({ rules: [{ type: "include", all: true }] });
// After the room ends, compose the recordings into one file
await client.video.v1.compositions.create({
roomSid,
audioSources: ["*"],
videoLayout: { grid: { video_sources: ["*"] } },
format: "mp4",
});Stream (Node.js)
const call = client.video.call("default", "my-room-name");
await call.startRecording({ recording_type: "composite" });
// ...and when you're done
await call.stopRecording({ recording_type: "composite" });Step 9: Leave
Twilio (Web)
room.disconnect();Twilio (iOS and Android)
room?.disconnect()Stream (Web, iOS, Android)
call.leave();On the web, call.leave() returns a promise, so you can await it.
Minimal-Change Checklist
If you want to move an existing Twilio Video app with as few changes as possible, work through these in order:
- Swap your token endpoint so your backend issues Stream user tokens instead of Twilio access tokens.
- Replace
connect()withclient.call(type, id)andcall.join(). - Replace track subscription events with participant state, which already tells you who's publishing audio, video, and screen share.
- Move room status callbacks to call webhooks, such as
call.session_started,call.ended, andcall.recording_ready. - Test recording end to end, since Twilio's Compositions step goes away.
Next Steps
Developers, we invite you to try building completely free with the Stream Video SDK of your choice. Create your Stream account to get started.
To see full working apps, browse the open-source SDKs and samples on GitHub:
- JavaScript and React, including sample apps
- iOS
- Android
- Flutter
If you're planning a larger migration, contact us to talk it through with our team.
