Guide · Developer
How to Add Video Calling to a React App
Add 1:1 and group video calls to a React or Next.js app with @voltkit-rtc/react: a token endpoint, a call page with hooks, video tiles, mute, chat and cost.
- Author
- VoltKit
- Published
- Reading time
- 9 min read
A React video call has three parts: a token from your backend, a provider that connects a client, and hooks that give you tracks to draw. @voltkit-rtc/react is the React SDK for VoltKit RTC: it handles the connection, reconnects and adaptive video, and the service runs the media servers, so there is no WebRTC server for you to run. By the end you will have a page where two or more people can join, see and hear each other, mute, turn the camera off and leave.
The code uses the Next.js App Router, but the hooks work in any React app. Only the server part changes: Build a token server has the same endpoint in Node.js, Spring Boot, Python, Go and PHP.
Before you start
You need a VoltKit account and an RTC project; the quickstart creates both and gives you the API base URL and secret. VoltKit may ask you to verify the account before you create a project, which takes a minute.
A new project starts with every media option off. Open the project's Settings tab, find Media and quality, and switch on video, which includes HD voice. Allowing a mode costs nothing by itself. Until you do, people can join the room but nobody can publish, and the SDK refuses the camera with the code media-disabled.
The SDK needs React and react-dom 18 or 19. Browsers offer the camera only on HTTPS or localhost.
Step 1: install the SDK
npm install @voltkit-rtc/react @voltkit-rtc/client
The client goes beside it, so your app and the hooks share one copy. The hooks read that client and render again when it changes, and everything on the JavaScript SDK page still applies. For a plain web page without React, the JavaScript SDK page shows the same room.
Step 2: get a token from your backend
The browser never holds your API secret. Your backend checks who the user is, decides the room and the role, and returns a short-lived token and the wsUrl to connect to:
// app/api/calls/[callId]/token/route.ts: runs on your server only
import { StreamClient } from "@voltkit-rtc/server";
import { currentUser, findCall } from "@/lib/calls"; // your own auth and data
const rtc = new StreamClient({
baseUrl: process.env.VOLTKIT_RTC_URL!,
apiKey: process.env.VOLTKIT_RTC_SECRET!, // never sent to a browser
});
export async function POST(request: Request, { params }: { params: Promise<{ callId: string }> }) {
const user = await currentUser(request);
if (!user) return Response.json({ error: "sign in first" }, { status: 401 });
const { callId } = await params;
const call = await findCall(callId);
if (!call || ![call.callerId, call.calleeId].includes(user.id)) {
return Response.json({ error: "not found" }, { status: 404 });
}
await rtc.ensureRoom({ roomId: call.id, hostIdentity: call.callerId });
const role = user.id === call.callerId ? "host" : "cohost";
const { token, wsUrl } = await rtc.createToken({ roomId: call.id, identity: user.id, role });
return Response.json({ token, wsUrl }, { headers: { "Cache-Control": "no-store" } });
}
Ask for a token right before joining. Tokens are short-lived (ten minutes by default), and the service refreshes them during the session.
Step 3: build the call page
This is the client side of a call: join, your camera and microphone, everyone's video and sound, mute, camera off and leave. It uses hooks, so it is a client component and starts with "use client".
// app/calls/[callId]/call-page.tsx
"use client";
import { useState } from "react";
import {
AudioTrack,
VideoTrack,
VoltkitProvider,
useLocalMedia,
useRemoteTracks,
useRoom,
type ClosedReason,
} from "@voltkit-rtc/react";
type Credentials = { token: string; wsUrl: string };
async function fetchCredentials(callId: string): Promise<Credentials> {
const res = await fetch(`/api/calls/${encodeURIComponent(callId)}/token`, { method: "POST" });
if (!res.ok) throw new Error(`Could not get a token (${res.status}).`);
return res.json();
}
const ENDED: Record<ClosedReason, string> = {
left: "You left the call.",
kicked: "You were removed from the call.",
"room-closed": "The call has ended.",
replaced: "You joined this call from another tab or device.",
"gave-up": "The connection was lost.",
};
export function CallPage({ callId }: { callId: string }) {
const [credentials, setCredentials] = useState<Credentials | null>(null);
const [attempt, setAttempt] = useState(0);
const [notice, setNotice] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
async function join() {
setBusy(true);
setNotice(null);
try {
setCredentials(await fetchCredentials(callId));
setAttempt((n) => n + 1); // a new key: a new provider with a fresh client
} catch (err) {
setNotice((err as Error).message);
} finally {
setBusy(false);
}
}
if (!credentials) {
return (
<main>
{notice && <p role="status">{notice}</p>}
<button onClick={join} disabled={busy}>
{busy ? "Joining…" : "Join the call"}
</button>
</main>
);
}
return (
<VoltkitProvider
key={attempt}
wsUrl={credentials.wsUrl}
token={credentials.token}
onClosed={(reason) => {
setCredentials(null);
setNotice(ENDED[reason]);
}}
>
<Call onRetry={join} />
</VoltkitProvider>
);
}
function Call({ onRetry }: { onRetry: () => void }) {
const { state, info, error, leave } = useRoom();
const local = useLocalMedia();
const videos = useRemoteTracks({ kind: "video" });
const sounds = useRemoteTracks({ kind: "audio" });
const [problem, setProblem] = useState<string | null>(null);
const report = (err: Error) => setProblem(err.message);
if (state === "idle" && error) {
return (
<main>
<p role="alert">Could not join: {error.message}</p>
<button onClick={onRetry}>Try again</button>
</main>
);
}
if (state === "idle" || state === "connecting") return <p>Joining…</p>;
const canPublish = info?.role === "host" || info?.role === "cohost";
const camera = local.stream?.getVideoTracks()[0];
return (
<main>
{state === "reconnecting" && <p role="status">Reconnecting…</p>}
{problem && <p role="alert">{problem}</p>}
<section className="tiles">
{camera && (
<figure className="tile">
<VideoTrack track={camera} mirror />
<figcaption>You</figcaption>
</figure>
)}
{videos.map((t) => (
<figure key={t.producerId} className="tile">
<VideoTrack track={t.track} producerId={t.producerId} />
<figcaption>{t.identity}</figcaption>
</figure>
))}
</section>
{sounds.map((t) => (
<AudioTrack key={t.producerId} track={t.track} />
))}
<footer>
{canPublish && !local.stream && (
<button onClick={() => local.publish().catch(report)}>Start camera and microphone</button>
)}
{local.stream && (
<>
<button onClick={() => local.setMicEnabled(!local.micEnabled).catch(report)}>
{local.micEnabled ? "Mute" : "Unmute"}
</button>
<button onClick={() => local.setCamEnabled(!local.camEnabled).catch(report)}>
{local.camEnabled ? "Turn camera off" : "Turn camera on"}
</button>
</>
)}
<button onClick={leave}>Leave</button>
</footer>
</main>
);
}
The page itself stays a server component:
// app/calls/[callId]/page.tsx
import { CallPage } from "./call-page";
export default async function Page({ params }: { params: Promise<{ callId: string }> }) {
const { callId } = await params;
return <CallPage callId={callId} />;
}
What each part does
- The provider makes the client in the browser, connects it, and closes it when it unmounts.
onClosedsays why a session ended. A closed session stays closed, so joining again mounts a new provider (a newkey) with a fresh token. publish()opens the camera and microphone and publishes them; only hosts and co-hosts may. With no options it sends the highest quality the project allows. Video quality has the sizes and the upload each one needs.- Your own tile is mirrored, as people expect.
producerIdon a remoteVideoTrackturns on adaptive stream: the video is received at the size it is shown and paused while it is off screen. AudioTrackplays each microphone, music and shared-screen sound. Joining from a click lets the browser play it.- The hooks follow the client. After
setMicEnabled(false),micEnabledis false in every component that usesuseLocalMedia(), and a reconnect shows asreconnectingwithout unmounting anything.
Step 4: add chat
There are no chat hooks: chat is on the client the provider holds. Listen with useVoltkitEvent and send with useVoltkitClient():
"use client";
import { useState } from "react";
import { RpcError, type ChatMessage } from "@voltkit-rtc/client";
import { useVoltkitClient, useVoltkitEvent } from "@voltkit-rtc/react";
export function Chat() {
const client = useVoltkitClient();
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [draft, setDraft] = useState("");
const [notice, setNotice] = useState<string | null>(null);
useVoltkitEvent("message", (m) => setMessages((list) => [...list, m])); // yours included
useVoltkitEvent("messageDeleted", ({ id }) => setMessages((list) => list.filter((m) => m.id !== id)));
async function send() {
if (!client || !draft.trim()) return;
try {
await client.sendMessage(draft);
setDraft("");
setNotice(null);
} catch (err) {
if (err instanceof RpcError && err.code === "chat-muted") setNotice("A moderator has muted you in this chat.");
else if (err instanceof RpcError && err.code === "rate-limited") setNotice("Slow down a little.");
else setNotice("Your message was not sent.");
}
}
return (
<aside>
<ul>
{messages.map((m) => (
<li key={m.id}>
<b>{m.from}</b> {m.text}
</li>
))}
</ul>
{notice && <p role="status">{notice}</p>}
<form
onSubmit={(e) => {
e.preventDefault();
void send();
}}
>
<input value={draft} onChange={(e) => setDraft(e.target.value)} />
<button disabled={!client}>Send</button>
</form>
</aside>
);
}
Chat messages are not billed. Live chat sets out what the room's chat does, including chat-only connections for people who only read along.
Step 5: test with two people
Open the page in two browsers, signed in as two different users. The same identity joining twice replaces its first session, which then ends with the message for replaced. Allow the camera, start it on both sides, and try mute, camera off, leaving and rejoining. Turn off Wi-Fi for a moment: the page shows "Reconnecting…" and comes back without unmounting. If you test from two devices in one room, put one of them on headphones, or each picks up the other's speakers and you hear echo; see Echo.
Group calls and roles
A group call is the same room with more people. Give everyone who should be on camera host or cohost; give people who only watch viewer, and they receive without publishing. Use a room id per call that nobody can guess. Hosts can mute, remove and promote people with the client from useVoltkitClient(); the moderation calls are on Rooms.
Next.js and server rendering
- Client components only. Every module of the package starts with
"use client", so importing it from a server component is fine. A component that calls its hooks must be a client component, as the call page is. - Nothing runs on the server. The provider makes its client in an effect, so no socket is opened and no browser API is read there, and the page hydrates without a mismatch.
- Do not make a
StreamClientduring render. Let the provider make it.
What a call costs
Each connected participant is billed per second, at the rate of the media they use. Someone who receives video pays the video rate, even with their own camera off:
2 people × 60 minutes = 120 participant-minutes
120 participant-minutes × 99 ÷ 1,000 = 11.88 credits, ₹11.88 (≈ $0.13) at today's rate
Full HD Video + HD Audio: 99 credits per 1,000 participant-minutes. Billed per second, so a 7½-minute call costs 7½ minutes.
Prices are in Indian rupees; dollar figures are approximate, at ₹95 per US dollar on 24 October 2026, for orientation only. You are billed in rupees.
8 people × 45 minutes = 360 participant-minutes
360 participant-minutes × 99 ÷ 1,000 = 35.64 credits, ₹35.64 (≈ $0.38) at today's rate
Full HD Video + HD Audio: 99 credits per 1,000 participant-minutes. Billed per second, so a 7½-minute call costs 7½ minutes.
Tokens, API calls and chat messages cost nothing. How much does a video calling API cost? works through whole months, and the participant-minute calculator works out your own session.
Where to go next
- React SDK: every hook and component, token refresh, wallet notices and the errors you will meet.
- Screen sharing and Video quality: the rest of a call.
- Add video calling to a React Native app: the same hooks on a phone.
- Add a video call to a Next.js app: the route handler, the server page and token refresh in the App Router.
- Migrating from Agora: Agora's calls and their VoltKit names.
Check a token while you develop
In code, treat the token as opaque. While you develop, the JWT Decoder shows a test token's expiry on your own device and never sends it anywhere:
Inspect a test token with theJWT DecoderUse test tokens only: a token is a credential for a room, and production tokens belong nowhere but the app that asked for them.
Frequently asked questions
How do I add video calling to a React app?
Install @voltkit-rtc/react and @voltkit-rtc/client. Your backend mints a token with your API secret and returns it with wsUrl. In the app, wrap the call in VoltkitProvider, publish with useLocalMedia, and draw the tiles from useRemoteTracks with VideoTrack and AudioTrack.
Does it work with Next.js?
Yes. Every module of the package starts with "use client", so a server component may import it, and a component that calls its hooks must be a client component. Nothing runs on the server, so no socket is opened there and the page hydrates without a mismatch.
Which versions of React does it need?
React and react-dom 18 or 19, with @voltkit-rtc/client 0.8 or 0.9 installed beside it. Types are included, and both ES modules and CommonJS work.
Where does the token come from?
From your backend. It checks who the user is, decides the room and the role, and calls VoltKit with your API secret. The browser never holds the secret.
Why does the camera not start on my test site?
Browsers offer the camera and microphone only on HTTPS or localhost. Also check that video is switched on under the project's Settings, Media and quality: a new project starts with every media option off, and the SDK then refuses with the code media-disabled.
Can I use it without React?
Yes. The hooks wrap the JavaScript SDK, @voltkit-rtc/client, which works in any web app with or without a framework. Everything on its page still applies: video quality, reconnection, chat, the events and the error codes.