WhatsApp Web Clone Part 2: Let's Add Video Calling

Let's Add Video Calling!
After a recent update to WhatsApp, users can now call each other directly from the web and desktop clients. In the previous part of this article series, we implemented a chat feature resembling WhatsApp chat using Stream's Chat SDK, we used Supabase to quickly get user authentication going and focussed most of our effort on making sure our implementation resembles WhatsApp.
In this part of the series, we want to take our project to the next level by adding user-to-user calling using the Stream Video Calling API. When using WhatsApp it is straightforward to step into a video call right from the chat you are having. Using Stream's Video SDK and UI components, we can get a similar user experience set up fast. Without a ready-to-use video calling API, we would have to create and configure our backend infrastructure, which can prove challenging when reliability, performance, and scale are all required.
Our code here is mostly based on the existing React Chat Integration Guide but we will be making a few customizations along the way to make things look more like WhatsApp.
Let's start where we left off in Part 1 of this series.
First, we need to add Stream Video as a dependency:
npm install @stream-io/video-react-sdk stream-chat-react stream-chatWe will also need to install sass, this will allow NextJS to compile and use some SASS-based templates taken directly from Stream's React Chat Integration Guide.
npm install sassThis will be a lot of code, but I will explain things as we go.
We first need to create a number of components and assets. These components are what tie our Chat and Video services together.
Create a file in the directory app/hooks named useDragable.ts
The contents should be:
import { useEffect, useRef } from "react";
const throttle = <T,>(fn: (arg: T) => void, delay: number) => {
let time = Date.now();
return (arg: T) => {
if (time + delay - Date.now() <= 0) {
fn(arg);
time = Date.now();
}
};
};
export const useDraggable = (element?: HTMLElement | null) => {
const dragStart = useRef<{ x: number; y: number } | null>(null);
useEffect(() => {
if (!element) return;
const handleMouseDown = (event: MouseEvent) => {
if (!(event.button === 0 && event.buttons === 1)) return;
const { left, top } = element.getBoundingClientRect();
dragStart.current = { x: event.clientX - left, y: event.clientY - top };
};
const handleMouseUp = () => {
document.removeEventListener("mousemove", handleDrag);
dragStart.current = null;
};
const handleDrag = (event: MouseEvent) => {
if (!dragStart.current) return;
const deltaX = event.pageX - dragStart.current.x;
const deltaY = event.pageY - dragStart.current.y;
element.style.left = deltaX + "px";
element.style.top = deltaY + "px";
};
element.addEventListener("mousedown", handleMouseDown);
document.addEventListener("mouseup", handleMouseUp);
document.addEventListener("mousemove", throttle(handleDrag, 100));
return () => {
element.removeEventListener("mousedown", handleMouseDown);
document.removeEventListener("mouseup", handleMouseUp);
document.removeEventListener("mousemove", handleDrag);
};
}, [element]);
};The aboce listing creates a helper object allowing an on screen element to be dragged and move within the browser window. We will use this component later in our project.
Next, we need to expose this file's interface. We do this by creating a file next to it called index.ts.
export * from "./useDraggable";To build our intended user interface, we need to create customized versions of 5 UI components provided by the Stream Video SDK.
- CreateCallButton
- ChannelHeader
- CustomEventComponent
- Channel
- Video
All these components are related. The Video component contains the Channel component, the Channel contains the ChannelHeader component, and the ChannelHeader contains the CreateCallButton. It's pretty straightforward when you see the result.
Let's begin with the CreateCallButton. This component will display a button in the UI that will initiate a video call. This component also contains a lot of the logic related to enabling Stream's Video SDK. Create a file named CreateCallButton.ts in the directory components/CreateCallButton.
The code should looks similar to this:
import { useCallback } from "react";
import {
MemberRequest,
useStreamVideoClient,
} from "@stream-io/video-react-sdk";
import { useChannel } from "stream-chat-react";
import { customAlphabet } from "nanoid";
const nanoid = customAlphabet(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
10,
);
export function meetingId(length = 12) {
return nanoid(length);
}
export const CreateCallButton = () => {
const videoClient = useStreamVideoClient();
const channel = useChannel();
const createCall = useCallback(() => {
videoClient
?.call("default", meetingId())
.getOrCreate({
ring: true,
data: {
custom: {
channelCid: channel.cid,
},
members: Object.values(channel.state.members).map<MemberRequest>(
(member) => ({
user_id: member.user_id!,
}),
),
},
})
.then((call) => {
console.log("call", call);
});
}, [videoClient, channel]);
const disableCreateCall = !videoClient;
return (
<button
className="rmc__button rmc__button--green"
disabled={disableCreateCall}
onClick={createCall}
>
<span>Start a call</span>
</button>
);
};We need to create an index.ts file next to the file we created as well.
Make it look as follows:
export * from "./CreateCallButton";Let's move on to the ChannelHeader. The 'ChannelHeader' is adjusted to act as a container for the CreateCallButton and display metadata like an avatar image and user name. Create a file ChannelHeader.ts in the directory components/ChannelHeader.
This one should look something like this:
import React from "react";
import type { ChannelStateData } from "stream-chat";
import {
asDynamicKey,
Avatar,
useChannel,
useChannelPreviewInfo,
useStateStore,
useTranslationContext,
WorkspaceNavigationBackButton,
} from "stream-chat-react";
import { CreateCallButton } from "../CreateCallButton";
// subtitle is a custom field, so declare it on the channel's custom data
declare module "stream-chat" {
interface CustomChannelData {
subtitle?: string;
}
}
export type ChannelHeaderProps = {
/** Manually set the image to render, defaults to the Channel image */
image?: string;
/** Show a little indicator that the Channel is live right now */
live?: boolean;
/** Set title manually */
title?: string;
};
const headerSelector = (state: ChannelStateData) => ({
data: state.data,
memberCount: state.memberCount,
watcherCount: state.watcherCount,
});
const UnMemoizedChannelHeader = (props: ChannelHeaderProps) => {
const { image: overrideImage, live, title: overrideTitle } = props;
const channel = useChannel();
const { data, memberCount, watcherCount } = useStateStore(
channel.state,
headerSelector,
);
const { t } = useTranslationContext();
const { displayImage, displayTitle } = useChannelPreviewInfo({
channel,
overrideImage,
overrideTitle,
});
const subtitle = data?.custom?.subtitle;
// v15's header is a three-column grid: start, data and end
return (
<div className="str-chat__channel-header">
<div className="str-chat__channel-header__start">
<WorkspaceNavigationBackButton />
<Avatar
imageUrl={displayImage}
userName={displayTitle}
size={channel?.type === "commerce" ? "2xl" : "lg"}
/>
</div>
<div className="str-chat__channel-header__data">
<div className="str-chat__channel-header__data__title">
{displayTitle}{" "}
{live && <span>{t(asDynamicKey("live"), "live")}</span>}
</div>
{subtitle && (
<div className="str-chat__channel-header__data__subtitle">
{subtitle}
</div>
)}
<div className="str-chat__channel-header__data__subtitle">
{!live && !!memberCount && memberCount > 0 && (
<>
{t("channelHeader.online.members.label", "{{ memberCount }} members", {
memberCount,
})}
,{" "}
</>
)}
{t("channelHeader.online.online.label", "{{ watcherCount }} online", {
watcherCount,
})}
</div>
</div>
<div className="str-chat__channel-header__end">
<CreateCallButton />
</div>
</div>
);
};
/**
* The ChannelHeader component renders some basic information about a Channel.
*/
export const ChannelHeader = React.memo(
UnMemoizedChannelHeader,
) as typeof UnMemoizedChannelHeader;And again an index.ts file is required.
export * from "./ChannelHeader";Next up is the CustomEventComponent. It renders system messages (for example, "Jane joined the chat") as a centered pill, the way WhatsApp shows them. Create a file CustomEventComponent.tsx in the directory components/CustomEventComponent:
import type { EventComponentProps } from "stream-chat-react";
export const CustomEventComponent = ({ message }: EventComponentProps) => {
if (message.type !== "system" || !message.text) return null;
return (
<div className="whatsapp-system-message">
<span>{message.text}</span>
</div>
);
};Add its styles to the end of components/layout.css:
.whatsapp-system-message {
display: flex;
justify-content: center;
margin: 0.5rem 0;
}
.whatsapp-system-message > span {
padding: 0.25rem 0.75rem;
border-radius: 0.5rem;
background: #ffffff;
color: var(--icons-color);
font-size: 0.8125rem;
box-shadow: 0 1px 0.5px rgba(11, 20, 26, 0.13);
}And, as with the other components, an index.ts file next to it:
export * from "./CustomEventComponent";Now, let's focus our attention on creating a channel view. It passes the CustomEventComponent to the SDK as the MessageSystem override.
Create the file Channel.tsx in the directory components/Channel.
This file should look as follows:
import {
MessageComposer,
MessageList,
ThreadHeader,
WithComponents,
} from "stream-chat-react";
import { ChannelSlot, ThreadSlot } from "stream-chat-react/slot-layout";
import { CustomEventComponent } from "../CustomEventComponent";
import { ChannelHeader } from "../ChannelHeader";
const overrides = { MessageSystem: CustomEventComponent };
export const Channel = () => (
<WithComponents overrides={overrides}>
<ChannelSlot slot="channel" fallback={<p>Select a conversation to start chatting</p>}>
<ChannelHeader />
<MessageList />
<MessageComposer focus />
</ChannelSlot>
<ThreadSlot slot="thread">
<ThreadHeader />
<MessageList />
<MessageComposer focus />
</ThreadSlot>
</WithComponents>
);Not too bad, right? We already did most of the work in the code we wrote earlier.
Make sure to add this implementation as an export as well. Create the file index.ts next to the Channel file.
export * from "./Channel";And finally, we need to add the Video component. Create a file called Video.tsx in components/Video. The Video component will contain the actual video call being performed by the Stream SDK. So, there is some logic involved with call state management.
The app opens no channel on load, so the CallPanel shows incoming and outgoing calls whatever channel is open: an incoming call rings even if its channel isn't open. Once the user joins a call, the panel opens the chat channel the call was started from (only once per call, so the user can still switch channels during the call).
import { StreamCall, useCalls } from "@stream-io/video-react-sdk";
import {
CallingState,
CancelCallButton,
PaginatedGridLayout,
RingingCall,
ScreenShareButton,
SpeakingWhileMutedNotification,
ToggleAudioPublishingButton,
ToggleVideoPublishingButton,
useCall,
useCallStateHooks,
} from "@stream-io/video-react-sdk";
import { useChatContext, useWorkspaceNavigation } from "stream-chat-react";
import { useEffect, useRef, useState } from "react";
import { useDraggable } from "../../app/hooks";
const CallPanel = () => {
const call = useCall();
const { useCallCallingState, useCallCustomData } = useCallStateHooks();
const callingState = useCallCallingState();
const customData = useCallCustomData();
const { client } = useChatContext();
const { isChannelActive, openChannel } = useWorkspaceNavigation();
const [panelElement, setPanelElement] = useState<HTMLDivElement | null>(null);
useDraggable(panelElement);
// Once the call is joined, open the chat channel it was started from, so
// the person who accepted it lands in the conversation. Only once per call,
// so the user can still navigate to other channels during the call.
const channelCid: string | undefined = customData.channelCid;
const openedCallChannel = useRef(false);
useEffect(() => {
if (callingState !== CallingState.JOINED || openedCallChannel.current) return;
openedCallChannel.current = true;
if (!channelCid || isChannelActive(channelCid)) return;
const [type, id] = channelCid.split(":");
// returns the instance the channel list already loaded, if there is one
const channel = client.channel(type, id);
// the channel slot renders an initialized channel; it does not query
(channel.initialized ? Promise.resolve() : channel.watch())
.then(() => openChannel(channel))
.catch((err) => console.error("Could not open the call channel", err));
}, [callingState, channelCid, client, isChannelActive, openChannel]);
if (!call) return null;
// Incoming and outgoing rings are shown whatever channel is open: the app
// opens no channel on load, so gating on the active channel would hide them.
if (callingState === CallingState.JOINED) {
return (
<div
className="str-video__call-panel rmc__call-panel-wrapper"
ref={setPanelElement}
>
<PaginatedGridLayout groupSize={4} />
<div className="rmc__active-call-controls">
<ScreenShareButton />
<SpeakingWhileMutedNotification>
<ToggleAudioPublishingButton />
</SpeakingWhileMutedNotification>
<ToggleVideoPublishingButton />
<CancelCallButton />
</div>
</div>
);
} else if (
[CallingState.RINGING, CallingState.JOINING].includes(callingState)
) {
return (
<div className="rmc__call-panel-wrapper" ref={setPanelElement}>
<RingingCall />
</div>
);
}
return null;
};
export const Video = () => {
const calls = useCalls();
return (
<>
{calls.map((call) => (
<StreamCall call={call} key={call.cid}>
<CallPanel />
</StreamCall>
))}
</>
);
};And again, we need an index.ts, with a single export.
export * from "./Video";That was a lot of code, but we are nearly there. Before we move towards integrating our Video component, let's ensure it'll all look somewhat decent.
Create a directory called styles in the components directory. In that directory, we need to add five files.

_layout.scss
body {
margin: 0;
font-family:
-apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu",
"Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family:
source-code-pro, Menlo, Monaco, Consolas, "Courier New", monospace;
}
html,
body {
margin: unset;
padding: unset;
height: 100%;
width: 100%;
}
#root,
.main-container {
display: flex;
width: 100%;
height: 100%;
}
.str-chat-channel-list {
position: fixed;
z-index: 1;
width: 0;
&--open {
width: 100%;
}
}
.str-chat-channel {
width: 100%;
}
.str-chat__thread {
width: 100%;
height: 100%;
position: fixed;
z-index: 1;
}
.str-chat__channel-header .str-chat__header-hamburger {
width: 30px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
border: none;
background: transparent;
svg {
width: 25px;
height: 25px;
}
&:hover {
svg path {
fill: var(--primary-color);
}
}
}
@media screen and (min-width: 768px) {
.str-chat-channel-list {
width: 100%;
max-width: 420px;
position: initial;
z-index: 0;
}
.str-chat__thread {
position: initial;
z-index: 0;
}
.str-chat__channel-header .str-chat__header-hamburger {
display: none;
}
}
@media screen and (min-width: 1024px) {
.str-chat__thread {
width: 45%;
}
.str-chat__channel-header .str-chat__header-hamburger {
display: none;
}
}CallPanel.scss
.rmc__call-panel-wrapper {
position: absolute;
top: 60px;
right: 20px;
}
.str-video__call-panel {
height: 350px;
.rmc__active-call-controls {
bottom: 10px;
display: flex;
justify-content: center;
gap: 10px;
}
.str-video__call-controls__button--variant-danger {
height: fit-content;
}
.str-video__participant,
.str-video__video-container {
display: flex;
}
}
.str-video__participant_details,
.str-video__notification {
color: #fff;
}ChannelPreview.scss
.rmc__channel-preview__call-controls {
display: flex;
gap: 0.5rem;
.str-video__call-controls__button {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
padding: 0;
.str-video__icon--call-accept {
width: 10px;
height: 10px;
}
.str-video__icon--call-end {
width: 12px;
height: 12px;
}
}
}SideBar.scss
#sidebar {
display: flex;
flex-direction: column;
border-inline-end: var(--str-chat__channel-list-border-inline-end);
.str-chat__channel-list {
border: none;
}
.rmc__button--logout {
svg {
rotate: 180deg;
}
}
}
#sidebar-footer {
display: flex;
width: 100%;
padding: 0.5rem;
}And finally, index.scss
@import "stream-chat-react/dist/css/index.css" layer(default-chat-sdk);
@import "@stream-io/video-react-sdk/dist/css/styles.css"
layer(default-video-sdk);
@import "layout";
@import "./CallPanel.scss";
@import "./ChannelPreview.scss";
@import "./Sidebar.scss";The final thing we need to do is integrate the Video components into the WhatsAppComponent we created earlier.
So open up the file components/WhatsAppChat.tsx.
Start with modifying the imports at the top of the file.
Replace all existing imports with the following.
import { useEffect, useMemo, useState } from "react";
import { ChannelPaginator, StreamChat } from "stream-chat";
import { ChannelNavigation, Chat, WithComponents } from "stream-chat-react";
import { ChatView } from "stream-chat-react/slot-layout";
import type { LayoutDescriptor } from "stream-chat-react/slot-layout";
import { Channel } from "./Channel";
import {
StreamTheme,
StreamVideo,
StreamVideoClient,
} from "@stream-io/video-react-sdk";
import { Video } from "./Video";
import "@stream-io/video-react-sdk/dist/css/styles.css";
import "./layout.css";
import "./styles/index.scss";
import { User } from "@supabase/supabase-js";
import ChannelListHeader from "./ChannelListHeader";
// our header replaces the channel list's default one
const channelListOverrides = { ChannelListHeader };Right below the declaration of the const chatClient = ... add a line declaring a useState variable.
const [videoClient, setVideoClient] = useState<StreamVideoClient>();The chat and video clients both need a token for the signed-in user. They get it from the route app/api/create-user/route.ts. The route reads the user from the Supabase session (it ignores any user ID in the request, and answers 401 when nobody is signed in), makes sure the user exists on Stream, and returns a token that expires after an hour:
import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { StreamClient } from "@stream-io/node-sdk";
export const dynamic = "force-dynamic";
// tokens expire after an hour; the client's tokenProvider fetches a new one
const TOKEN_VALIDITY_IN_SECONDS = 60 * 60;
export async function POST() {
// 1 only a signed-in user gets a token, and only for their own user ID
const supabase = createRouteHandlerClient({ cookies });
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
return NextResponse.json({ error: "Not signed in" }, { status: 401 });
}
// 2 make sure the user exists on Stream's backend
const apiKey = process.env.NEXT_PUBLIC_REACT_APP_STREAM_KEY || "Set API Key";
const apiSecret = process.env.REACT_APP_STREAM_SECRET || "Set API Secret";
const client = new StreamClient(apiKey, apiSecret);
await client.upsertUsers([{ id: user.id }]);
// 3 generate a short-lived user token for the chat and video clients
const token = client.generateUserToken({
user_id: user.id,
validity_in_seconds: TOKEN_VALIDITY_IN_SECONDS,
});
return NextResponse.json({
userToken: token,
});
}Back in WhatsAppChat.tsx, the user ID must be the signed-in user's (const userId = user.id;), since that's who the route issues tokens for. Replace the useEffect that connects the chatClient with the following. Instead of a fixed token, both clients get a tokenProvider that fetches a token from the route. They call it when they connect, and again whenever the token expires. After the chat client, it creates and connects a StreamVideoClient:
useEffect(() => {
// the same user, as the video client expects it
const chatUser = { id: userId };
// Fetches a token for the signed-in user. The chat and video clients call
// it on connect and again whenever the token expires.
const tokenProvider = async () => {
const res = await fetch("/api/create-user", { method: "POST" });
if (!res.ok) throw new Error(`Token request failed: ${res.status}`);
const response: { userToken: string } = await res.json();
return response.userToken;
};
const connect = async () => {
await chatClient.connectUser({ id: userId }, tokenProvider);
const _videoClient = new StreamVideoClient(apiKey);
await _videoClient.connectUser(chatUser, tokenProvider);
setVideoClient(_videoClient);
// make sure this line is after the setting of the video client
setIsLoading(false);
};
connect().catch((err) => console.error("Failed to connect", err));
}, [apiKey, chatClient, userId]);And finally, we replace this bit of code:
{
!isLoading && (
<div id="root">
<Chat client={chatClient}>
<ChatView
layouts={layouts}
views={{
channels: (
<>
<div className="channel-list-container">
<WithComponents overrides={channelListOverrides}>
<ChannelNavigation />
</WithComponents>
</div>
<ChannelSlot slot="channel" fallback={<p>Select a conversation to start chatting</p>}>
<ChannelHeader />
<MessageList />
<MessageComposer />
</ChannelSlot>
<ThreadSlot slot="thread">
<ThreadHeader />
<MessageList />
<MessageComposer />
</ThreadSlot>
</>
),
}}
/>
</Chat>
</div>
);
}Replace it with this:
{
!isLoading && videoClient && (
<div id="root">
<Chat client={chatClient}>
<StreamVideo client={videoClient}>
<StreamTheme as="main" className="main-container">
<ChatView
layouts={layouts}
views={{
channels: (
<>
<div className="channel-list-container">
<WithComponents overrides={channelListOverrides}>
<ChannelNavigation />
</WithComponents>
</div>
<Channel />
<Video />
</>
),
}}
/>
</StreamTheme>
</StreamVideo>
</Chat>
</div>
);
}As in part 1, the app loads with no conversation open, so pick one in the channel list first. The video below shows a call started from a conversation after selecting it.
Moving Onward to Deployment
In part two of this article series we covered how to add video calling to the chat application we built in part 1. You can see how powerful Stream's UI components are, and how straightforward they are to integrate into a project.
In part 1 you learned how easy it is to add chat to a product, and how quickly we could implement an authentication layer using Supabase's authentication feature.
If you enjoyed this article, please drop a ⭐️ star ⭐️on the sample GitHub repository.
To learn more about Stream's Video product, click here.
And remember, you will need a trial account sign-up to get started using Stream. If you followed along with this article series, you already have created an account with Stream. But, in case you haven't, Stream provides powerful UI components and infrastructure to build any chat and video use case you can dream of. You can add reliable and scalable chat and/or video to your project in about a week instead of months. Most importantly, by using Stream's Chat and Video, you are relying on our global edge network, providing a reliable, scalable infrastructure suitable for any scale.
We also have a Maker account available for small projects and non-commercial projects.
We have created a nice codebase, we can run this locally. But what about showing it to the world? Let's look into deployment next. In part 3 of this article series we will look at deploying our project to Vercel. Vercel is the creator and maintainer of the NextJS framework, and their infrastructure is perfectly suitable to deploying a cloud API based project like our WhatsApp clone.
So let's look at deployment in part 3.
