WebRTC: Peer Connections, Signaling, and ICE
WebRTC is the browser's peer-to-peer real-time engine: audio, video, and arbitrary data flowing directly between two browsers with encryption built in and latency measured in tens of milliseconds. It is the technology behind every in-browser video call product, and unlike the marketing suggests, the browser API is only the middle of the system. Two peers cannot find each other without an out-of-band signaling channel, and a meaningful fraction of real-world connections cannot establish directly without a TURN relay. Understanding which piece is which is most of understanding WebRTC.
This lesson builds the two-peer path end to end: capture a media stream, exchange offers and answers, walk ICE to a working candidate pair, and open a DataChannel β then covers the production realities that demos skip.
The Three Actors
| Piece | Role |
|---|---|
| MediaStream | Captured audio and video tracks from camera, microphone, or screen |
| RTCPeerConnection | The peer-to-peer session: negotiation, encryption, media transport |
| Signaling channel | Any server or channel that carries offers, answers, and ICE candidates between peers |
Nothing in the WebRTC API defines how signaling works. A WebSocket server, a plain HTTP poll, or a shared database all qualify; the messages themselves are JSON blobs the API tells you to send. That flexibility is deliberate β teams already have realtime infrastructure β and it is also why a minimal working demo needs a small server you did not have to write for a fetch example.
Capture Local Media
async function acquireLocalVideo(container) {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: { width: { ideal: 1280 }, height: { ideal: 720 } },
audio: { echoCancellation: true, noiseSuppression: true }
});
const localVideo = document.getElementById('local-video');
localVideo.srcObject = stream;
localVideo.muted = true; // never route your own audio back to yourself
return stream;
} catch (error) {
if (error.name === 'NotAllowedError') {
showPermissionHelp();
} else if (error.name === 'NotFoundError') {
showNoDeviceMessage();
}
throw error;
}
}
function stopStream(stream) {
for (const track of stream.getTracks()) track.stop();
}
Two habits matter here. The local video element must be muted, or the user hears their own audio echoed through the speakers β the single most common first-call bug. And stopping tracks when the call ends is not optional cleanup: an active getUserMedia stream keeps the camera's hardware indicator lit, which users correctly read as a privacy failure.
The Offer and Answer Handshake
Both peers create an RTCPeerConnection, add their local tracks, and then one side β usually the one that joins first β creates an offer. The other answers. Candidates discovered during ICE flow across the same signaling channel as they appear:
const config = {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'turn:turn.example.com', username: 'user', credential: 'token' }
]
};
const pc = new RTCPeerConnection(config);
const localStream = await acquireLocalVideo();
for (const track of localStream.getTracks()) {
pc.addTrack(track, localStream);
}
pc.ontrack = (event) => {
const remoteVideo = document.getElementById('remote-video');
remoteVideo.srcObject = event.streams[0];
};
pc.onicecandidate = (event) => {
if (event.candidate) {
signaling.send({ type: 'candidate', candidate: event.candidate });
}
};
async function startCall() {
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
signaling.send({ type: 'offer', description: offer });
}
signaling.onmessage = async (message) => {
if (message.type === 'offer') {
await pc.setRemoteDescription(message.description);
const answer = await pc.createAnswer();
await pc.setLocalDescription(answer);
signaling.send({ type: 'answer', description: answer });
} else if (message.type === 'answer') {
await pc.setRemoteDescription(message.description);
} else if (message.type === 'candidate') {
await pc.addIceCandidate(message.candidate);
}
};
The order of setLocalDescription and setRemoteDescription is not interchangeable, and candidates that arrive before the remote description is set must be queued until it is β a race that shows up as a call that connects only on the second attempt. Modern code can also request ICE candidates via addTransceiver and let negotiation proceed without perfect candidate plumbing, but the explicit dance above remains what every debugging session assumes.
ICE, STUN, and TURN
ICE is the connectivity framework that finds a path between two peers. Each side gathers candidate pairs β local interfaces, server-reflexive addresses discovered through STUN, and relay addresses from TURN β and they run connectivity checks until one pair works.
STUN answers the question "what does the internet see as my address," which is enough when both peers are on friendly networks. TURN relays the actual media when direct paths fail: corporate NATs, symmetric carriers, and CGNAT mobile networks account for a substantial share of real calls. Budget for TURN capacity from the beginning, monitor the percentage of calls falling back to it, and understand that relaying costs you bandwidth in both directions β the economics of a video product often turn on this one line item.
DataChannels: WebRTC Beyond Media
The same peer connection carries arbitrary data:
const dc = pc.createDataChannel('app-state', { ordered: true });
dc.onopen = () => dc.send(JSON.stringify({ type: 'hello', at: Date.now() }));
dc.onmessage = (event) => applyRemoteState(JSON.parse(event.data));
dc.onclose = () => showReconnectHint();
// On the other side
pc.ondatachannel = (event) => {
const channel = event.channel;
channel.onmessage = (e) => applyRemoteState(JSON.parse(e.data));
};
The ordered flag and an optional maxPacketLifeTime trade delivery guarantees against latency; game state and cursor points often prefer unordered with short lifetimes, while document edits want ordered delivery. DataChannels are SCTP under the hood β reliable, congestion-controlled transport over the same DTLS-encrypted path as the media β and they make peer-to-peer features like local file drop or shared whiteboards possible without a media pipeline at all. The bufferedAmount property on a channel tells you how much data is queued for transmission; check it before pushing large blobs, and wait for the bufferedamountlow event when you are streaming, or a slow link will balloon the send queue until the page stutters.
Screen Sharing and Track Replacement
Swapping the camera for a screen mid-call is track surgery rather than renegotiation: capture with getDisplayMedia, then replace the outgoing video track through the existing sender:
async function shareScreen(pc) {
const screen = await navigator.mediaDevices.getDisplayMedia({ video: true });
const videoTrack = screen.getVideoTracks()[0];
const sender = pc.getSenders().find((s) => s.track && s.track.kind === 'video');
if (sender) await sender.replaceTrack(videoTrack);
videoTrack.onended = () => {
// User pressed the browser's "stop sharing" control
sender.replaceTrack(cameraTrack);
};
}
The onended hook is mandatory: the browser's own stop-sharing button ends the screen track without notifying your application, and without a handler the remote side keeps seeing a frozen last frame of your screen.
Production Realities
Stats come free through pc.getStats, which reports per-candidate-pair round-trip time, packet loss, and bitrate β wire a lightweight stats poll into any debugging build and you can tell whether a bad call is the network or your code. Handle permission loss gracefully: a mid-call camera revocation should mute your tile and offer a retry, not throw an unhandled rejection. And plan renegotiation for the real lifecycle of a call β mute toggles that disable tracks, participants joining late, the aforementioned screen swap β because a demo that only implements join and leave is about a fifth of a shippable product.
Connection state changes surface through the connectionState and iceConnectionState properties, and listening to them is how you replace a frozen remote tile with a reconnecting indicator:
pc.addEventListener('connectionstatechange', () => {
switch (pc.connectionState) {
case 'connecting':
showStatus('Connectingβ¦');
break;
case 'connected':
showStatus('In call');
break;
case 'disconnected':
showStatus('Connection interrupted');
break;
case 'failed':
showStatus('Call failed β retrying');
restartIce();
break;
case 'closed':
teardownUi();
break;
}
});
function restartIce() {
if (pc.restartIce) pc.restartIce();
}
A brief disconnected state often recovers on its own as ICE re-checks pairs, so delay any heavy reaction; failed, on the other hand, needs intervention β restartIce triggers a new gathering round without a full renegotiation, which keeps the call alive through a momentary network switch from Wi-Fi to cellular.
Group calls change the topology. A full mesh of peer connections works for two or three participants and collapses beyond that, because every added participant multiplies everyone's upstream bandwidth. Production group products insert a selective forwarding unit or a multipoint control unit between peers: the browser still runs one RTCPeerConnection, but it connects to the server rather than to every other client. The browser-side API barely changes β the signaling messages target the SFU instead of a peer β which is exactly why it is worth understanding the two-party path deeply before layering on group infrastructure.
Common Mistakes
Forgetting to queue ICE candidates that arrive before setRemoteDescription
Fix: Buffer candidates until the remote description is set, then add them in order.
Leaving the local video element unmuted
Fix: Set muted on your own video element so the microphone does not feed back through the speakers.
Not stopping MediaStream tracks when a call ends
Fix: Call track.stop() on every track β users watch the camera indicator light.
Ignoring onended on a getDisplayMedia track
Fix: Restore the camera track when the user stops sharing from the browser UI.
Shipping without TURN and assuming direct connections always work
Fix: Provision TURN, measure relay usage, and include credentials in your ICE configuration.
Key Takeaways
- WebRTC is peer-to-peer media plus data, but it needs an external signaling channel you design yourself.
- RTCPeerConnection handles negotiation, DTLS encryption, and transport; MediaStream carries the tracks.
- The offer-answer dance plus ICE candidate exchange must be ordered and race-aware.
- STUN discovers public addresses; TURN relays media when direct paths fail β budget for TURN.
- DataChannels give reliable or lossy ordered delivery over the same connection as the media.
- Mute local video, stop tracks on teardown, and handle display-track onended to ship a professional call.