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"}
- The offer contains, among others,
m=application 9 UDP/DTLS/SCTP webrtc-datachannel(a data channel over SCTP encrypted with DTLS),a=fingerprint:sha-256 ...(the encryption key's fingerprint) anda=max-message-size:262144(256 KB per message in Chromium and WebKit). SCTP is a protocol for sending messages. DTLS is encryption like TLS, for UDP (a way of sending data packets with no promise that they arrive). - The order of the steps in that code is required.
createAnswer()before receiving an offer throwsInvalidStateError: ... PeerConnection cannot create an answer in a state other than have-remote-offer or have-local-pranswer.channel.send()beforeopenthrowsInvalidStateErrortoo.
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.
- Host candidate: an address on the local network. Browsers hide the local IP behind a random
...localname (mDNS, a name that only works on the local network), as in the output above. On the laundry's own Wi-Fi, this is enough. - NAT: the home or carrier router that lets many devices share one public IP (the address seen from the internet). A device behind NAT doesn't know its own public address.
- STUN: a small server that answers "from outside, you look like this IP:port". The result is an
srflxcandidate, your public address. Cheap, because it is one question and one answer. - TURN: a server that relays every byte when a direct connection doesn't get through (strict NAT, a company firewall). Because all traffic goes through it, TURN costs bandwidth (the amount of data that passes). A price as of October 2026: Cloudflare Realtime TURN at $0.05 per GB outbound (free when used with their SFU, a server that forwards media).
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
- The server needs to know the data. An order status must be stored in the database, so it goes through the server anyway (WebSocket or SSE). The laundry's status news doesn't need WebRTC.
- One to many. Sending to 10,000 phones means 10,000 connections from one tablet. Broadcasting needs a server (or an SFU).
- Networks that block UDP. Everything goes through TURN, and you pay for its bandwidth.
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?
- Candidates not passed on, or arriving before the offer.
addIceCandidatebeforesetRemoteDescriptionthrowsInvalidStateError: ... The remote description was null. - Only testing on the same network. In the field, NAT and firewalls make it fail without TURN.
getUserMediaover plain HTTP.navigator.mediaDevicesdoesn't exist outside a secure context.- Thinking signaling is part of WebRTC. You build it, and it should be protected by authentication like any other event.
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.