Real-Time & Streaming From Zero · Episode 03
WebRTC: Peer to Peer
WebRTC: Peer to Peer is Episode 03 of Real-Time & Streaming From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
You are about to watch a real video call connect — peer to peer, with no server,
no second computer, and no second person. How? Because you are both peers.
The page below creates two genuine RTCPeerConnection objects, has one of
them call the other, and streams live video across the connection that forms
between them. It is not a mock. It is not a fake. It is the exact same WebRTC handshake
that powers Google Meet, Discord calls, and every "drop a link, jump on a call" app you
have ever used — just folded in half so both ends live in one tab.
WebRTC has a reputation for being terrifying: SDP, ICE, STUN, TURN, signaling servers, NAT traversal. Most of that complexity exists to get two strangers' packets across the hostile open internet. Strip that away — put both peers in the same page — and what's left is small, legible, and kind of beautiful: an offer, an answer, and a trickle of ICE candidates. Step the demo through six stages and you'll see the whole conversation happen, line by line. By the end, the handshake won't be scary; it'll be obvious.
The colored blobs are a synthetic camera — a canvas painted at 30fps
and turned into a real MediaStream, so the demo is alive the instant the
page loads, with no permission prompt. Hit connect (or just walk the
stages) to run the real handshake; flip source → camera to send your
actual webcam across the same loopback. Everything degrades gracefully: if WebRTC or
the camera is unavailable, the synthetic source keeps playing and nothing throws.
The problem WebRTC solves (and the part we're skipping)
Every networking demo so far in this series went through a server. Your bytes left your machine, hit a box in a datacenter, and came back. That's fine for a chat message. It's miserable for live video: every frame pays a detour, and the company running the server pays for every gigabyte. WebRTC's promise is direct: media flows straight from one browser to the other, machine to machine, with the server out of the hot path entirely.
But two browsers can't just "find each other." They sit behind routers, NATs, and firewalls; neither knows the other's real address; and even once they do, they have to agree on codecs, encryption keys, and which network paths to try. WebRTC's answer is a structured negotiation:
Notice steps 2→3 and 5→6 require handing a blob of text from one peer to the other. That courier — the thing that carries the offer and answer between strangers — is called the signaling channel, and WebRTC pointedly does not define it. You can use a WebSocket, a QR code, or carrier pigeon. In production it's a tiny server whose only job is to relay these two messages until the peers connect directly, then get out of the way.
Here is the trick that makes this episode work with zero infrastructure: when both peers live in the same page, you are the signaling channel. Peer A's offer is just a JavaScript variable you hand to peer B by calling a method. No WebSocket, no server, no pigeon. The handshake is 100% real; the courier is a function call. (Real cross-internet signaling — and the STUN/TURN servers that punch through NATs — is Season 2. For loopback, we need none of it.)
Stage 1 — Two peer connections
We start by constructing both ends and doing nothing else, so you can see their
initial state. An RTCPeerConnection is born in signalingState:
"stable" and connectionState: "new" — alive, configured, but with no
idea the other exists. They are two strangers in the same room who haven't spoken.
In the demo, A and B render as two side-by-side panels. Right now both read
new / stable. Nothing connects them yet. That's the point: a peer
connection on its own is inert. It needs an offer to come to life.
Stage 2 — The offer
Peer A makes the first move. createOffer() asks A's WebRTC engine:
"describe yourself — what media can you send, what codecs do you speak, what's your
encryption fingerprint?" The answer comes back as SDP (Session
Description Protocol): a chunk of plaintext, one key=value per line, that is
the entire proposal for the call.
Then — and this ordering is the whole ballgame —
A calls setLocalDescription(offer). That's A committing: "this is officially
my offer." Only after setting it locally does the offer become something you can hand to
B. Flip on show SDP in the demo to read the actual bytes; it looks
intimidating but it's just a structured description of one side of a call.
Stage 3 — The answer
B receives A's offer (in our case: a function call) and reverses the dance.
setRemoteDescription(offer) tells B "here's what A proposed."
createAnswer() produces B's counter-proposal — the codecs and parameters B
agrees to, again as SDP. B commits with setLocalDescription(answer), and
finally the answer travels back so A can call
setRemoteDescription(answer).
That's six calls in a fixed order, and the order is non-negotiable:
A.createOffer()A.setLocalDescription(offer)B.setRemoteDescription(offer)B.createAnswer()B.setLocalDescription(answer)A.setRemoteDescription(answer)
Get them out of sequence and WebRTC throws an
InvalidStateError — it is a state machine, and these are the only legal
transitions. After step 6, both peers have a complete picture of the call. They've
agreed on what to send. Now they need to figure out where to send it.
Stage 4 — ICE candidates
The SDP says what; ICE (Interactive Connectivity Establishment)
finds where. As soon as you set a local description, each peer starts gathering
candidates — possible network addresses it can be reached at — and fires
an onicecandidate event for each one. Your job is to ferry every candidate
to the other peer and feed it in with addIceCandidate(). This drip-feed is
called trickle ICE: candidates flow continuously while connectivity is
probed, instead of waiting to gather them all first.
In loopback there's no NAT to defeat, so the candidates are all host
candidates — your machine's own local addresses. (That's why we need no STUN server: the
fancier srflx and relay candidate types only matter when peers are
across the internet.) Watch the demo: candidates pop up under A and B as little
addresses, the two sides probe each other, and
connectionState climbs new → connecting → connected. The
moment it hits connected, a direct channel exists between A and B. The pipe is
open.
Stage 5 — Add a track
Now the payoff. We take the synthetic MediaStream and attach its video
track to peer A with A.addTrack(). WebRTC carries it across the connection,
and peer B's ontrack event fires with the stream — which we drop straight
into a <video> element as B's remote feed.
Sit with what just happened: the blobs are generated on A's side, encoded, sent over a real peer connection, decoded on B's side, and painted as a remote video — all inside one tab. The left panel is "the camera"; the right panel is "what the other person sees." Flip source → camera and that remote feed becomes your actual face, round-tripped through genuine WebRTC. That's a video call. You built it.
Stage 6 — It's a real connection
To prove there's nothing up our sleeve, the last stage reads the connection's vital
signs. connectionState and iceConnectionState report
connected. And getStats() — the same diagnostic API behind
every "connection quality" indicator you've seen — returns live numbers: bytes sent,
bitrate, round-trip time. Watch the bitrate tick as the synthetic video streams. Fake
data can't produce real RTT measurements. This is a live media session, and you can read
its pulse.
How the code works
The heart of it is one async function that runs the handshake in order, with both peers as local variables. Read it top to bottom and you've read all of WebRTC's core:
// The entire handshake, both ends, in one function. No server.
async function rtcLoopback(localStream, onRemoteStream) {
const A = new RTCPeerConnection();
const B = new RTCPeerConnection();
// trickle ICE straight across — we ARE the signaling channel
A.onicecandidate = e => e.candidate && B.addIceCandidate(e.candidate);
B.onicecandidate = e => e.candidate && A.addIceCandidate(e.candidate);
// B receives A's media here
B.ontrack = e => onRemoteStream(e.streams[0]);
// attach the local stream to A BEFORE creating the offer,
// so the offer advertises the video track
if (localStream)
localStream.getTracks().forEach(tr => A.addTrack(tr, localStream));
// THE ORDER MATTERS — this is the only legal sequence:
const offer = await A.createOffer();
await A.setLocalDescription(offer);
await B.setRemoteDescription(offer);
const answer = await B.createAnswer();
await B.setLocalDescription(answer);
await A.setRemoteDescription(answer);
return { A, B }; // ICE now trickles + connects on its own
}
The ICE cross-wiring is two lines, and it's the part people most often get backwards. Each peer's own candidates must be fed to the other peer — A's go into B, B's go into A:
// A discovers an address → hand it to B
A.onicecandidate = (e) => {
if (e.candidate) B.addIceCandidate(e.candidate);
};
// B discovers an address → hand it to A
B.onicecandidate = (e) => {
if (e.candidate) A.addIceCandidate(e.candidate);
};
// the final e.candidate === null means "done gathering" — skip it
Receiving remote media is one event. When a track arrives on B, drop the stream onto a
<video>. The attributes matter as much as the JavaScript — without
muted, the browser refuses to autoplay it:
// <video id="remote" autoplay playsinline muted></video>
B.ontrack = (e) => {
const video = document.getElementById('remote');
if (video.srcObject !== e.streams[0])
video.srcObject = e.streams[0]; // the REMOTE feed, on B's side
};
And reading the live connection: addTrack is what sends media, while
connectionState and getStats() are how you observe the real
session. getStats() returns a Map of typed report objects you
walk through:
// attach media (this triggers renegotiation if done after connect)
sender = A.addTrack(track, stream);
// is it actually up?
console.log(A.connectionState); // "connected"
console.log(A.iceConnectionState); // "connected" / "completed"
// read live numbers from the real session
const stats = await A.getStats();
stats.forEach((report) => {
if (report.type === 'outbound-rtp')
console.log('bytes sent:', report.bytesSent);
if (report.type === 'candidate-pair' && report.nominated)
console.log('RTT (s):', report.currentRoundTripTime);
});
That's the whole API surface for a basic call. Everything else — reconnection, bandwidth control, simulcast — is built on these same primitives.
Common pitfalls
- Handshake order is law. It must be
createOffer → setLocalDescription → setRemoteDescriptionon A's offer, thencreateAnswer → setLocalDescription → setRemoteDescriptionfor the answer. Skip or reorder a step and you get anInvalidStateError. The peer connection is a state machine; these are its only legal moves. - setRemoteDescription before addIceCandidate. A peer can't accept candidates until it knows who they're for. If candidates arrive before the remote description is set, queue them and flush after — or you'll see "remote description was null" errors. (In loopback they're naturally in order, but real signaling races, so build the queue.)
- Feed candidates as they arrive — don't drop them. Trickle ICE
means
onicecandidatefires repeatedly. Every non-null candidate must reach the other peer viaaddIceCandidate. Ignore them and the connection never reachesconnected. The finalnullcandidate just signals "done gathering" — don't try to add it. - The remote
<video>won't play withoutmutedandautoplay(plusplaysinlineon iOS). Browsers block autoplay of audible media; a muted element is allowed. Forgetmutedand you get a frozen first frame and a silent failure. - No STUN needed here — but you'll need it for real. Loopback peers
reach each other with
hostcandidates (local addresses), so the config can be empty. Two browsers across the internet are behind NATs and need a STUN server to discover their public address (srflxcandidates), and a TURN relay when even that fails. That's Season 2. - Add the track before creating the offer. The offer's SDP is a
snapshot of what A intends to send.
addTrackfirst and the video is advertised in the offer; add it after and you must renegotiate (a fresh offer/answer round) — which is exactly Exercise 2.
Exercises
- Add an audio track too. Generate a tone with an
AudioContext+OscillatorNode, grab a track viaMediaStreamAudioDestinationNode.stream, andA.addTrack()it alongside the video before the offer. Confirm B'sontracknow fires twice (one audio, one video). Bonus: unmute the remote<video>after a click and hear it loop back. - Renegotiate after connect. Once the call is up, add a second track
to A. Notice nothing happens until you run a new
createOffer → setLocalDescription → setRemoteDescription → createAnswer → …cycle. WebRTC even firesonnegotiationneededto tell you. This is how "turn on your camera mid-call" works. - Print the candidate types. In
onicecandidate, parsee.candidate.candidate(or reade.candidate.type) and log whether each ishost,srflx, orrelay. In loopback you'll see onlyhost. Then add{ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] }to theRTCPeerConnectionconfig and watchsrflxcandidates appear — your public address, discovered.
What's next
Episode 04 — Data Channels. Video isn't the only thing that flows
peer to peer. RTCDataChannel gives you a direct, low-latency pipe for
arbitrary bytes over the same connection you just built — send chat messages,
sync game state, and transfer files browser-to-browser with no server touching the data.
We'll wire it onto this exact loopback, then make it do something fun.