Peer-to-peer browser multiplayer with WebRTC data channels. A tested peer module with perfect negotiation, a reliable ordered channel and a fast unordered channel, ICE restart, connection stats; a host-and-guests (star) helper where one browser runs the game; signaling through a WebSocket server, Bash room messages or any relay; STUN and TURN, NAT limits, host migration, what P2P can and can't ...
Download skill (.zip) Files on GitHubWebRTC multiplayer
Browsers connect directly to each other. Good for 2-8 friends, cheap to run, low latency. You still need:
- Signaling: a way to pass a few setup messages (offer, answer, network candidates) before the direct link exists.
Options: websocket-multiplayer’s server (
signal {to, data}is relayed between players in the same room), Bash room messages in a kit (sendto the room, ignore messages not addressed to you), or any small relay. - STUN (free, public) to find each player’s address. Included: Google’s STUN servers.
- TURN for strict networks (some mobile carriers, offices): roughly 10-20% of pairs can’t connect directly. TURN relays the traffic and costs bandwidth: a paid service (for example Cloudflare Calls, Twilio, Metered) or your own coturn. Without it, some players just can’t join: say so in the error (“Couldn’t connect to the host. Try another network.”).
assets/peer.js
import { createPeer, createStar } from "./peer.js";
const peer = createPeer({ polite: myId > theirId, signal: (data) => relay({ to: theirId, data }) });
onRelay((from, data) => from === theirId && peer.handle(data));
peer.connect(); // both sides may call it at once
peer.on("open", () => peer.send("reliable", { t: "hello" }));
peer.on("message", (channel, msg) => {});
peer.send("fast", { x, y }); // unordered, never resent: positions (a late one is useless)
await peer.stats(); // { rtt, relay }: relay true = going through TURN
Perfect negotiation: either side can start (and add voice later); on a clash the “polite” side gives way. Both peers must agree who is polite: compare ids.
Host and guests (createStar)
One browser (the host) runs the game, exactly like a server: guests send inputs and the host sends snapshots. Reuse the
websocket-multiplayer rules shape (move, tick, snapshot) in the host’s page, and network-synchronization and
multiplayer-prediction on the guests.
const star = createStar({ me, host, signal: (to, data) => relay({ to, data }) });
star.sync(playerIds); // whenever the room list changes
onRelay((from, data) => star.handleSignal(from, data));
star.on("join", (id) => ...); star.on("leave", (id) => ...); star.on("message", (from, channel, msg) => ...);
star.broadcast("fast", snapshot); star.send(hostId, "fast", input);
- The host can cheat (it is the server). Fine among friends; for rankings use a real server.
- Host leaves = game over unless you migrate: pick the next host the same way everyone agrees (oldest player, multiplayer-lobbies does this), send the latest full state to them regularly, and reconnect everyone to the new host.
- A phone host that locks its screen pauses the game for everyone. Prefer a computer as host and warn the host.
- Mesh (everyone to everyone) only for voice or under 4 players; connections grow as n x (n-1)/2.
Tested
In Chromium: two peers that both start at once (glare) connect through perfect negotiation, 50 reliable messages arrive
in order, the fast channel works, stats report a direct path; a host with two guests connects both, broadcasts reach guests,
and removing a guest from sync closes only that link; voice tracks were added later on the same connection (renegotiation).
assets/tests/rtc-test.html is that test: serve the multiplayer-and-online folder, open the page in Chromium started with
--use-fake-device-for-media-stream --use-fake-ui-for-media-stream, wait about 10 s, and read window.out.
Test your own game in one page with a fake relay (signal: (d) => setTimeout(() => other.handle(d), 10)), then two real devices on
different networks (phone on mobile data plus a laptop on wifi) before calling it done.
Pitfalls
No TURN plan, both sides polite (or neither), sending big JSON on the fast channel (over 16 KB fails; keep messages small),
forgetting bufferedAmount backpressure (handled: fast sends are skipped when congested), trusting the host for rankings, and
running in a preview iframe that blocks it. Data channels work in iframes, but test the direct link too.