WebRTC Basics — Realtime

WebRTC connects two browsers directly for media or a data channel (a line for data), encrypted. There is an RTCPeerConnection (the connection object) at each…

Eko's tablet and Mrs. Rini's are on the same Wi-Fi, a few metres apart. Yet every piece of news from Eko still goes up to the server before it reaches Mrs. Rini's board. Can they talk directly? They can, through WebRTC (Web Real-Time Communication): the browser API for direct connections between two browsers (peer-to-peer), for audio and video, or any data through a data channel (a line for data). Everything that goes through it is encrypted.

But before Mrs. Rini at the counter and Eko at the washing machines can throw notes straight to each other, they need to exchange "addresses and how to talk" through the office. Once each knows how to reach the other, the office no longer takes part. In this picture, throwing notes straight across is the data channel, and the office is a server. The "addresses" are ICE candidates and "how to talk" is SDP, both explained below.

Two peers and one data channel

Each end of the connection (called a peer) has one RTCPeerConnection, the browser's WebRTC connection object. The one who starts (Mrs. Rini) creates the data channel and an offer, and the one receiving (Eko) replies with an answer. The offer and the answer are SDP (Session Description Protocol): text describing what will be sent and the encryption keys.

This code runs both peers on one page. Each peer keeps its own SDP with setLocalDescription and the other peer's SDP with setRemoteDescription. The onicecandidate lines pass addresses (ICE candidates) on to the other peer:

const rini = new RTCPeerConnection()
const eko = new RTCPeerConnection()
// on the same page, "send it to the other peer" is just a direct function call
rini.onicecandidate = (e) => e.candidate && eko.addIceCandidate(e.candidate)
eko.onicecandidate = (e) => e.candidate && rini.addIceCandidate(e.candidate)

const channel = rini.createDataChannel('board')
channel.onopen = () => channel.send(JSON.stringify({ id: 12, status: 'Ready for pickup' }))
eko.ondatachannel = (e) => { e.channel.onmessage = (m) => console.log('eko got', m.data) }

rini.createOffer()
  .then((offer) => rini.setLocalDescription(offer).then(() => eko.setRemoteDescription(offer)))
  .then(() => eko.createAnswer())
  .then((answer) => eko.setLocalDescription(answer).then(() => rini.setRemoteDescription(answer)))

Run in Chromium 147 (and also in Firefox 146 and WebKit 26.4). This is the log of that run. The number on the left is the time of each line, in milliseconds:

   24 ms offer type offer sdp bytes 458
   29 ms rini candidate candidate:4100380318 1 udp 2113937151 54fed8ec-...-7dc9ef9b0b62.local 63524 typ host ...
   80 ms rini connectionState connected
   81 ms rini channel open, readyState open maxMessageSize 262144
   82 ms eko got {"id":12,"status":"Ready for pickup"}

ICE, NAT, STUN and TURN

An ICE candidate is one address the other peer might use to reach you (IP, port, protocol). ICE (WebRTC's way of finding a path) tries pairs of candidates (one of yours, one of the other peer's) until one gets through.

The list of STUN and TURN servers is given when the RTCPeerConnection is created:

const pc = new RTCPeerConnection({
  iceServers: [
    { urls: 'stun:stun.example.com:3478' },
    { urls: 'turn:turn.example.com:3478', username: 'laundry', credential: 'a-short-lived-secret' },
  ],
})

The credential (the TURN password) in that code is only an example. If a fixed TURN password is written in browser code, anyone can read it and use your TURN server, and you pay for the bandwidth. Keep the TURN key on the server, and create a short-lived password for each session. An example with Cloudflare Realtime TURN:

// server: the TURN key lives only here, in an environment variable
async function makeIceServers() {
  const res = await fetch(
    `https://rtc.live.cloudflare.com/v1/turn/keys/${process.env.TURN_KEY_ID}/credentials/generate-ice-servers`,
    {
      method: 'POST',
      headers: { Authorization: `Bearer ${process.env.TURN_KEY_API_TOKEN}`, 'Content-Type': 'application/json' },
      body: JSON.stringify({ ttl: 3600 }), // the password is valid for 1 hour
    },
  )
  if (!res.ok) throw new Error(`TURN ${res.status}`)
  return (await res.json()).iceServers
}

Call makeIceServers() from an endpoint that only logged-in staff can reach, then use the result in the browser: new RTCPeerConnection({ iceServers }). The list from Cloudflare already includes turns:turn.cloudflare.com:443?transport=tcp, which is TURN over TLS on port 443. This route still gets through on company networks that only allow HTTPS.

Signaling over the Socket.IO server you already have

WebRTC deliberately doesn't say how offers, answers and candidates get delivered. That delivery is called signaling, and you build it. The laundry's Socket.IO server already exists, so it only has to pass them on. In this code, pc is the RTCPeerConnection on each tablet:

// server: only passes them on, never reads them
io.on('connection', (socket) => {
  socket.join('rtc:board')
  socket.to('rtc:board').emit('peer-ready')
  socket.on('signal', (data) => socket.to('rtc:board').emit('signal', data))
})

// both tablets
pc.onicecandidate = (e) => { if (e.candidate) socket.emit('signal', { candidate: e.candidate }) }
socket.on('signal', async (d) => {
  if (d.sdp) {
    await pc.setRemoteDescription(d.sdp)
    if (d.sdp.type === 'offer') {
      await pc.setLocalDescription(await pc.createAnswer())
      socket.emit('signal', { sdp: pc.localDescription })
    }
  } else if (d.candidate) await pc.addIceCandidate(d.candidate)
})
// Mrs. Rini's tablet, on 'peer-ready':
// await pc.setLocalDescription(await pc.createOffer()); socket.emit('signal', { sdp: pc.localDescription })

Guess first: the two tablets are connected through a data channel, with this Socket.IO server as the go-between at the start. If Mrs. Rini's Socket.IO connection is cut, does her next message still reach Eko's tablet?

Tried with two pages (Chromium 147 with Chromium 147, and Chromium 147 with Firefox 146) and a socket.io 4.8.4 server: the server relayed 6 signals (offer, answer, 2 + 2 candidates), 1,942 bytes of JSON in all. Then Mrs. Rini's tablet ran socket.disconnect(), and the next message over the data channel still reached Eko's tablet. The server is only needed for the introduction.

Camera and microphone

navigator.mediaDevices.getUserMedia({ video: true, audio: true }) asks for camera and microphone permission, and the tracks (the audio or video streams) are added with pc.addTrack(). It only exists in a secure context (HTTPS or localhost). Tried in all three browsers over http://192.168.x.x: navigator.mediaDevices is undefined, while RTCPeerConnection is still there. A video call with a customer is outside this lesson.

When WebRTC is the wrong tool

WebRTC fits what goes straight between two people and is heavy or latency-sensitive (the delay must be as small as possible): voice and video calls, screen sharing, or sending a large file between tablets on the same Wi-Fi without putting load on the server.

⚠️ Why do the two tablets never connect?

TL;DR: WebRTC connects two browsers directly for media or a data channel (a line for data), encrypted. There is an RTCPeerConnection (the connection object) at each end, createDataChannel, then an offer and an answer as SDP (text describing the content and the encryption keys), and ICE candidates (addresses that might work) in both directions. You build the delivery of offers, answers and candidates (signaling) yourself, for example through a Socket.IO room. Once connected, data no longer goes through the server. On a local network host candidates (local addresses) are enough. Over the internet you need STUN, a server that tells you your public address, and TURN, a relay server paid per GB, when the direct path doesn't get through. Camera and microphone need a secure context (HTTPS or localhost) and permission. For status news that must be stored and broadcast to many phones, keep using a server.

⚡ Straight between browsers

Write:

const channel = rini.createDataChannel('board')
channel.onopen = () => channel.send(JSON.stringify({ id: 12, status: 'Ready for pickup' }))
eko.ondatachannel = (e) => { e.channel.onmessage = (m) => console.log('eko got', m.data) }

Meaning: WebRTC connects two browsers directly (peer-to-peer), for audio, video, or any data through a data channel (a line for data). In this code, rini and eko are RTCPeerConnections, the WebRTC connection objects on Mrs. Rini's tablet and Eko's tablet. rini creates the data channel and sends a status when the channel opens, and eko logs the message that arrives. Before the channel opens, the one who starts creates an offer and the one receiving replies with an answer, both as SDP (text describing the content and the encryption keys).

⚡ The server is only for the introduction

Guess first: the two tablets are connected through a data channel. At the start, the Socket.IO server passed on their offer and answer. If Mrs. Rini's Socket.IO connection is cut, does her next message still reach Eko's tablet?

It still arrives. The server only passes on the offer, the answer and the candidates (addresses that might work) for the introduction. That delivery is called signaling. Once connected, data no longer goes through the server.

Meaning: WebRTC does not say how signaling works, so you build it, for example through a Socket.IO room.

⚡ STUN and TURN

Meaning: On a local network host candidates (addresses on the local network) are enough. Over the internet you need STUN, a server that tells you your public address, and TURN, a server that relays every byte (paid per GB), when the direct path does not get through.

⚡ When it is not WebRTC

Meaning: Status news that must be stored in the database and broadcast to many phones still goes through a server. WebRTC fits what goes straight between two people and is heavy or latency-sensitive (the delay must be as small as possible), such as voice and video calls.

What you will learn