Blog

WebRTC signaling server: what it does, and build or buy

· Andrij Tkachenko · 11 min read

A small server in the middle with a bell above it, a dashed line running from it to a browser window on each side, and a solid line joining the two windows directly underneath

A WebRTC signaling server passes the offer, the answer and the network addresses between two browsers so they can connect, and then stays out of the way: no picture or sound ever goes through it. WebRTC leaves it to you, so you either write one, most often on a websocket, or use a service that already runs one.

Passing messages on is a dozen lines. The work is everything a call needs around them: who is signed in, who may call whom, ringing every tab, stopping the ring, and noticing that someone is gone. This post builds a signaling server (signalling, in British spelling) in Node.js that does those things, runs it against real browser tabs, and then lists what it still lacks, so you can decide whether to build yours.

What signaling carries

Message What it is for
Offer and answer What each side sends, and how it is encrypted
Candidates The addresses each browser may be reached at
Ring, accept, hang up The call itself: yours to design

The first two are WebRTC. Each browser makes them, and the other one has to receive them before any media flows (how WebRTC connects two browsers shows that exchange line by line). How they travel is not part of WebRTC. RFC 8825, the overview of the whole protocol suite, puts the choice of signaling outside its scope, and RFC 9429, which describes the browser API, leaves "addressing, retransmission, forking, and glare handling" to the application. For sending a stream to a media server there is a standard, WHIP (RFC 9725), an HTTP POST of the offer. For calls between your users there is none.

The third row is the part people underestimate. The server never needs to read an offer or a candidate, and MDN says as much. It does need to know who is calling whom, which is why a signaling server is mostly a server about your users.

A signaling server in Node.js

This one uses the ws package (8.23 here). A page connects with a token your app signed for its user, and the server keeps every tab of every user. A call rings all the tabs of the person called, belongs to the first tab that answers, and from then on offers, answers and candidates pass only between those two tabs:

signaling.mjs
import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
import { WebSocketServer } from 'ws';

const SECRET = process.env.SIGNALING_SECRET;
const RING_MS = 30_000;
const BEAT_MS = 10_000;

const tabs = new Map();  // user id → the sockets of that user, one a tab
const calls = new Map(); // call id → { id, from, to, caller, callee, timer }

// Your app signs "42.<hmac>" into the page of user 42. Nobody else can make one.
function userOf(token = '') {
  const [user, mac] = token.split('.');
  const good = createHmac('sha256', SECRET).update(user).digest();
  const given = Buffer.from(mac ?? '', 'hex');
  return given.length === good.length && timingSafeEqual(given, good) ? user : null;
}

// Your own check: friends, a booking, a block list.
async function mayCall(from, to) {
  return from !== to;
}

const send = (socket, message) => socket?.readyState === 1 && socket.send(JSON.stringify(message));

function end(call, reason, by) {
  if (!calls.delete(call.id)) return;
  clearTimeout(call.timer);
  const ringing = call.callee ? [] : [...(tabs.get(call.to) ?? [])];
  for (const socket of [call.caller, call.callee, ...ringing]) {
    if (socket !== by) send(socket, { type: 'ended', call: call.id, reason });
  }
}

const handlers = {
  async call(socket, { to }) {
    if (!(await mayCall(socket.user, String(to)))) return send(socket, { type: 'refused' });
    const ring = tabs.get(String(to));
    if (!ring?.size) return send(socket, { type: 'unavailable', to });

    const call = { id: randomUUID(), from: socket.user, to: String(to), caller: socket, callee: null };
    call.timer = setTimeout(() => end(call, 'missed'), RING_MS);
    calls.set(call.id, call);
    send(socket, { type: 'ringing', call: call.id });
    for (const tab of ring) send(tab, { type: 'ring', call: call.id, from: call.from });
  },

  accept(socket, { call: id }) {
    const call = calls.get(id);
    if (!call || call.to !== socket.user || call.callee) return send(socket, { type: 'refused' });
    call.callee = socket; // the first tab to answer has the call
    clearTimeout(call.timer);
    send(call.caller, { type: 'accepted', call: id });
    for (const tab of tabs.get(call.to)) {
      if (tab !== socket) send(tab, { type: 'ended', call: id, reason: 'answered_elsewhere' });
    }
  },

  // Offers, answers and candidates: passed on unread, only between the two sockets of the call.
  signal(socket, { call: id, data }) {
    const call = calls.get(id);
    const other = call?.caller === socket ? call.callee : call?.callee === socket ? call.caller : null;
    if (!other) return send(socket, { type: 'refused' });
    send(other, { type: 'signal', call: id, data });
  },

  hangup(socket, { call: id }) {
    const call = calls.get(id);
    if (!call) return;
    if (call.caller === socket || call.callee === socket) end(call, 'hangup', socket);
    else if (!call.callee && call.to === socket.user) end(call, 'declined', socket);
  },
};

const wss = new WebSocketServer({
  port: 8080,
  maxPayload: 64 * 1024,
  verifyClient({ req }, done) {
    req.user = userOf(new URL(req.url, 'http://localhost').searchParams.get('token') ?? '');
    done(Boolean(req.user), 401);
  },
});

wss.on('connection', (socket, req) => {
  socket.user = req.user;
  socket.alive = true;
  if (!tabs.has(socket.user)) tabs.set(socket.user, new Set());
  tabs.get(socket.user).add(socket);

  socket.on('pong', () => { socket.alive = true; });
  socket.on('message', (raw) => {
    let message;
    try { message = JSON.parse(raw); } catch { return; }
    if (Object.hasOwn(handlers, message?.type)) handlers[message.type](socket, message);
  });
  socket.on('close', () => {
    tabs.get(socket.user).delete(socket);
    for (const call of [...calls.values()]) {
      if (call.caller === socket || call.callee === socket) end(call, 'left', socket);
    }
  });
});

// A tab whose network died never says goodbye: ask, and drop the ones that stay silent.
setInterval(() => {
  for (const socket of wss.clients) {
    if (!socket.alive) { socket.terminate(); continue; }
    socket.alive = false;
    socket.ping();
  }
}, BEAT_MS);

The page is the one from the JavaScript post with two changes. It wraps each description and candidate as { type: 'signal', call, data }, and it creates its RTCPeerConnection only once the call is accepted, the caller on accepted and the person called as they press Answer. Both may then offer at the same moment, which the perfect negotiation pattern in that post settles.

What the test showed

We ran it with Chromium 156 tabs on fake cameras, and with plain Node.js clients for the people who should be refused. The ring time was set to 3 seconds and the beat to 1 second for the run, in place of the 30 and 10 above:

Case Result
A forged token, or none HTTP 401, no connection
A call to someone with two tabs both ring
One tab answers the other stops ringing
Picture after the answer both ways in 609 ms
Someone else sends into the call refused, nothing delivered
A caller the app refuses refused, no ring
A call to someone off line unavailable at once
Nobody answers missed after 3,002 ms
Declined in one tab caller told, other tab stops
The caller closes the tab other side told in 9 ms
The network of the caller dies other side told in 835 ms

What stands behind the rows:

  • The token is the whole sign-in. The server trusts the user id only because your app signed it. A third user, properly signed in, sent an offer with the id of a call that was not theirs, then tried to accept it and to hang it up. The server refused the first two and ignored the third, and neither browser in the call received anything. Without that check, anyone who learns a call id can talk into it. A token in the address of a websocket ends up in server logs, so make it short-lived.
  • Every tab rings, one answers. The person called had two tabs. Both rang with the same call, the first to answer took it, and the other got answered_elsewhere and stopped. This needs the server to hold a connection for every tab of every user, all the time, not only during calls.
  • Nothing is exchanged before the answer. While the call rang, neither browser had received a single signal. That is on purpose. Candidates are addresses, and RFC 8826 notes that the caller learns the IP addresses of the other person as soon as their candidates arrive, and suggests holding the negotiation back until they have answered. Otherwise calling someone is a way to find out where they are.
  • A closed tab and a dead network are different. Closing the tab closes the websocket, and the other side knew in 9 ms. A laptop lid shut or a train in a tunnel closes nothing, so the server asks every socket to answer a ping and drops the silent ones. With a beat of 1 second that took 835 ms here, and it can take up to two beats. Without it, the other person looks at a frozen picture until they give up.
  • Signaling is small. The call that connected took 10 messages through the server, 18,123 bytes in all, and nothing after that. The load on a signaling server is the open connections, not the traffic.

What this server still lacks

It holds for calls between two people on one process. None of what follows was in the test, and all of it stands between this file and a product:

  • More than one process. tabs and calls live in memory. With two processes behind a load balancer, the caller is on one and the person called may be on the other, so a ring has to cross between them, through something like Redis, and the state of each call has to live somewhere both can read. Websockets in Node.js past one server goes through what that takes.
  • A reload ends the call. Here a closed socket ends its call at once. A real one gives the tab a few seconds to come back and carries the new offer that restartIce() makes when a phone moves from Wi-Fi to mobile data (why a WebRTC connection fails).
  • Relays. Signaling only introduces the two browsers. Behind many office and mobile networks they still can't reach each other without a TURN server, with logins your server makes for each user and lets expire (what free and public TURN servers give you, and what STUN and TURN do).
  • Phones and closed tabs. Someone with no tab open is unavailable. Ringing a phone whose app is closed goes through the push service of the phone, which is a separate system to build and keep working.
  • Group calls. Three or more people need rooms, a list of who is in, and soon a media server that the signaling has to drive (how group video calls work).
  • Running it. TLS for wss://, limits on how fast one user may ring another, deploys that don't hang up every call in progress, and someone who is told when it is down. A signaling server that is down means no call can start, however healthy everything else is.

Build or buy

Part If you build it
Passing offers and candidates An afternoon, as above
Sign-in and who may call Yours either way: only your app knows
Ringing every tab and device A connection per tab, kept open all day
More than one server Shared state and a message bus
Relays for blocked networks TURN servers in each region you serve
Group calls Media servers, and signaling for them

Building makes sense when your app already holds a websocket for every user, your calls are between two people, and you have someone who will own it. The server above is a fair start, and nothing in it is hard.

It stops making sense when signaling is the only reason you would run a websocket fleet at all, or when the list in the last section is longer than the feature you set out to add. The one part no service can take from you is the second row: who may call whom is a question about your users, and it should stay in your code whoever carries the messages. How to choose a video call API lists what to ask of a service before you rely on it.

The same call with no signaling server

With WordPlus Cloud, that second row is all you write. Your app decides who may call in a route of its own, which answers a token for the call. In Express, with the @wordplus/realtime package:

JavaScript
// server.mjs: GET /call-token?to=34&type=video, which the button asks as it is pressed.
app.get('/call-token', async (req, res) => {
  // Your own check goes here: who may call whom.
  const me = req.session.userId;
  if (!me) return res.sendStatus(401);
  res.json({ token: await realtime.callToken(me, req.query.to, { type: req.query.type }) });
});

The page starts the call screen and puts a button where people call from:

JavaScript
await rt.callScreen(); // the ring and the call window, on every page a call may ring on
HTML
<call-button to="34" token-url="/call-token" type="video" name="Ann">Call Ann</call-button>

The call rings in every tab and on every device Ann has open, and stops ringing everywhere once she answers in one. It goes straight between the two browsers when their networks allow it, through our relays on ports 443 and 80 when they don't, and through our media servers when even the relays can't reach, moving from one to the next without hanging up. Calls between two people are encrypted end to end on every path. With no token from your route nothing starts, so nobody gets around your check.

The calls page of the Express guide shows the rest: group calls with a host, adding people to a call, and a call interface of your own. The same works from PHP and Python.

Calls for your app

WordPlus Cloud for Apps is priced by concurrent connections, starting from 1,000, billed monthly or yearly, and calls between two people take no credits on any path. See video calls and group calls for apps, or the apps pricing. Questions about your integration? Write to us.