Projects / Chat

P2P Chat

A peer-to-peer chat app and the reusable engine under it. Messages, files, voice notes and calls travel over WebRTC data channels. Signaling can use Firebase, a Cloudflare Durable Object, or nothing at all. Use the engine through a two-call Peer API, or drop down to the engines for full control.

Launch Chat App App v4.0.0 engine.js v1.5.0
Contents
  1. Architecture Overview
  2. Quick Start — the Peer API
  3. ChatEngine — Firebase Signaling
  4. CloudflareWSEngine — Durable Object Signaling
  5. DirectEngine — No-Backend Direct Mode
  6. Connection Quality — STUN, TURN and Route Detection
  7. Group Chats — Host Relay
  8. Full API Reference
  9. Usage Examples
  10. Data Types
  11. Firestore Schema
  12. Production Checklist
  13. Troubleshooting — Known Failure Modes
  14. Reference Apps
  15. The Chat App
01 / Overview

Architecture

The engine splits communication into two layers: signaling (finding the other peer and swapping connection details) and data transfer (an RTCDataChannel). Once the channel is open the signaling service is no longer involved. Every message travels directly between browsers, or through a TURN relay when a direct path is impossible.

The three engines share one interface, so the app can swap them without changing how it sends or receives. They differ only in how the first handshake happens.

On top of them sits Peer, a PeerJS-style layer: one call to host a room, one call to join, one Connection object per remote peer, standard events, automatic reconnect. It is the simple tier. The engines are the advanced tier: you drive signaling, relay and media yourself. Both live in engine.js and the advanced tier is fully backward compatible, so existing apps keep working unchanged.

Your appChat App, DeepBlue IDE collab, a card game: anything that needs a live link between browsers protocol.js msg-features.js file-transfer.js call-1to1.js drive-sync.js send · on('message') or send · onMessage(cb) engine.js v1.5.0Two tiers in one file: start simple, drop down when you need control SIMPLE Peer Connection host() · join() · auto-reconnect · events ADVANCED ChatEngine CloudflareWSEngine DirectEngine BaseEngine Peer is built on the engines below it, so everything it does you can also do by hand. Firestoresignals/ offer · answer · ICE Durable ObjectWebSocket signal relay WebRTCRTCPeerConnection · DataChannel
Fig. 1 — One file, two tiers. Most code only needs Peer. The engines underneath are public and unchanged.
EngineSignalingNeedsUse it for
ChatEngineFirestore documentsFirebase projectRooms and inboxes where peers join at different times
CloudflareWSEngineWebSocket to a Durable ObjectFirebase ID tokenLive signaling with no Firestore round trips; used for the app’s Cloudflare rooms and groups
DirectEngineYou copy and paste SDPNothingOffline or serverless use

Which tier?

Simple: PeerAdvanced: engines
Set up a roomPeer.host(room, opts) / Peer.join(room, opts)new Engine(), init, callbacks, createRoom / joinRoom
Who is on the other endconn.peer (a stable id you choose) and conn.metadataA throwaway engine id per link
ReconnectAutomatic, with backoff and a retry budgetYou rebuild the engine and rejoin
Timeouts and errorsTyped errors: auth, signaling, timeout, connection-lostonError and onSignaling hooks; no join timeout
Debuggingdebug: true and peer.getTrace()Console logs
Group relay, media tracks, Direct modeNot covered. Reach the engine with peer.engineFull control
TopologyStar: guests talk to the host, the host talks to all guestsStar, with optional relay: true host
02 / Simple API

Quick Start: the Peer API

Peer wraps an engine. Host a room or join one, and you get Connection objects that work like small event emitters. It signals through Cloudflare by default (you pass a Firebase ID token) or through Firebase (you pass a Firestore handle).

import { Peer } from '/Projects/Chat/engine.js';

const token = () => firebase.auth().currentUser.getIdToken();   // a string, or an async function

// Host: resolves once signaling is open and guests can join
const host = await Peer.host('my-room-123', { token, id: 'alice' });
host.on('connection', conn => {
  console.log(conn.peer, 'joined', conn.metadata);
  conn.on('data', msg => console.log(conn.peer, msg));
  conn.on('close', ({ reason }) => console.log(conn.peer, 'left:', reason));
});
host.send({ type: 'announcement', text: 'Welcome' });          // to every guest

// Guest, in another browser: resolves once the host answered and the channel is open
const guest = await Peer.join('my-room-123', { token, id: 'bob', metadata: { name: 'Bob' } });
guest.on('message', ({ from, data }) => console.log(from, data));
guest.send({ type: 'chat', text: 'Hello!' });                  // to the host
host(room)signaling opens join(room)guest makes an offer Offer + answervia signaling ICE candidatesdirect or TURN Channel openshello swaps ids open event ConnectedFrames go straight between browsers. The signaling socket is no longer needed. send · on('data') ping every 5 s 10 s of silence = lost route-change event link lost leave on purpose Reconnecting network drop, sleeping tab, host restart guest retries: 1s, 2s, 4s ... up to 15s, 5 times then it is back at join(). Host sees peer-left. Clean exit disconnect() or conn.close() a bye frame goes first, so the other side does not retry (close reason: host-closed)
Fig. 2 — The life of a Peer link, from host() and join() to a clean exit or a reconnect.

Options

OptionDefaultDescription
signaling'cloudflare''cloudflare' needs token. 'firebase' needs db.
tokennoneA Firebase ID token, or an async function returning one. A function is called again on every signaling reconnect, so the token never goes stale.
dbnonefirebase.firestore(), when signaling is 'firebase'.
idrandomYour Peer id. The other side sees it as conn.peer. Pick something stable, such as a Chat ID.
metadatanullAny JSON value. The other side receives it as conn.metadata.
reconnect{ retries: 5, baseMs: 1000, maxMs: 15000 }Guests rejoin automatically and hosts re-open a lost signaling socket. false turns it off.
connectTimeoutMs20000How long a guest waits for the host to answer, and how long a host waits for signaling to open.
heartbeatMs · timeoutMs · graceMs5000 · 10000 · 8000Ping interval, silence before a peer is dropped, and the time a disconnected link gets to recover.
debugfalsetrue logs to console.debug. A function receives each { t, msg } entry. peer.getTrace() always holds the last 200.
createEnginenone(engineOptions) => engine. Plug in your own signaling. The object must implement the shared engine interface.

Peer events

EventPayloadWhen
openidHost: signaling is open. Guest: connected to the host. Fires once.
connectionconnHost: a guest connected and the two sides have swapped ids.
message{ from, data, connection }Any incoming data, from any connection.
peer-leftconnHost: a guest left or was lost.
route-change{ peer, connection, relayed, local, remote }The route is known (direct or TURN relay) or has changed.
reconnecting{ attempt, delayMs, reason }Guest: the link was lost or a connect failed, so it retries after delayMs. reason is 'connection-lost', 'timeout' or 'signaling'.
reconnectednoneGuest: the link is back. Host: signaling is back.
disconnectednoneHost: lost the signaling server. Connected guests stay connected, but nobody new can join until reconnected.
signaling(state, info)The signaling socket: 'connecting', 'open', 'reconnecting', 'failed' or 'closed'.
track{ stream, from, connection }A remote media stream arrived. Media has to be added through peer.engine.
errorError with .typeSee the error types below.
close{ reason }The Peer is finished: 'local', 'host-closed', 'lost' or 'error'.

Connection

A host gets one Connection per guest. A guest has one, to the host, at peer.connection.

MemberReturnsDescription
conn.peerstringThe remote Peer id (their id option). Falls back to "host" or the engine id if the remote is not a Peer.
conn.metadataanyWhat the remote passed as metadata.
conn.openbooleanTrue while you can send.
conn.relayedboolean | nulltrue when a TURN relay carries the link, false when it is direct, null until known.
conn.send(data)booleanTrue if the frame was handed to the channel. Before open, and while a guest reconnects, it is queued (up to 100) and sent when the link opens.
conn.close()voidHost: kick this guest. Guest: the same as peer.disconnect().
conn.channel · conn.pcobject | nullEscape hatches to the RTCDataChannel and RTCPeerConnection.
events'open' (again after a reconnect), 'data', 'close', 'route', 'reconnecting'.

Reconnect policy

Guests. When the channel dies, the connect times out or signaling fails, the Peer waits baseMs × 2attempt−1 (capped at maxMs) and joins again with a fresh engine and a fresh token. The Connection object stays the same, so your handlers stay attached: it emits reconnecting, then open again. After retries failed attempts, join() rejects (if it never connected) or the Peer closes with reason 'lost'.

Hosts. A lost signaling socket is re-opened the same way, and guests that are already connected are unaffected. A guest that reconnects reaches the host as a new Connection (a new connection event, and peer-left for the old one) with the same conn.peer.

Clean exits do not retry. disconnect() and conn.close() send a goodbye frame first, so the other side closes with a reason instead of reconnecting. Frames whose __peer field is a string are the Peer layer's own hello and goodbye frames; avoid that field name in your data.

Error types

error.typeMeaning
authNo token, or the token function threw. A missing token is thrown by host() and join() before anything connects.
signalingThe signaling server is unreachable, or a Firestore stream broke.
timeoutThe host did not answer within connectTimeoutMs, or signaling did not open in time.
connection-lostA guest lost the host and used up its retries.
unavailableNo WebRTC in this browser, no room name, or a Peer that was already used. A Peer is single-use: make a new one.

Debugging, and your own signaling

const peer = await Peer.join('my-room-123', { token, debug: true });   // also logs to console.debug
console.table(peer.getTrace());                                         // last 200 entries: [{ t, msg }, ...]
peer.on('route-change', ({ peer: id, relayed }) => console.log(id, relayed ? 'TURN relay' : 'direct'));

// Bring your own signaling: return anything that implements the shared engine interface
const custom = new Peer({ createEngine: opts => new MyEngine(opts) });

The interface is createRoom, joinRoom, send, sendTo, closePeer, disconnect, the on… callbacks (onMessage, onPeerConnected, onPeerDisconnected, onRoute, onTrack, onError) and a peers map. onSignaling and reconnectSignaling are optional.

What the simple tier leaves out on purpose: guests only talk to the host (use new ChatEngine({ relay: true }) for a transparent group relay), and media is not negotiated for you (the engines negotiate once, at connect time). Reach the engine with peer.engine when you need either.
03 / Firebase Mode

ChatEngine

ChatEngine uses Firebase Firestore as a rendezvous server. The host listens to signals for new offers, and each guest writes one document under its own id. ICE candidates are trickled into that document as they appear, including slow TURN relay candidates.

Guest joinRoom(id) Firestore chatRooms/{id}/signals Host createRoom(id) createRoom: watch signals signals/{guestId} = offer snapshot: new offer answer + hostCandidates snapshot: answer guestCandidates (trickled) RTCDataChannel · peer to peer Firestore is idle from here on
Fig. 3 — Firebase signaling. Only the offer, answer and candidates pass through Firestore.
Prerequisites: The host page must call firebase.initializeApp(config) and pass firebase.firestore() to engine.init() before calling any room methods.
import { ChatEngine } from '/Projects/Chat/engine.js';

// Assumes firebase.initializeApp() already called on this page
const engine = new ChatEngine();
engine.init(firebase.firestore());

// Register callbacks before joining
engine.onPeerConnected(peerId => console.log('peer joined:', peerId));
engine.onPeerDisconnected(peerId => console.log('peer left:', peerId));
engine.onMessage((data, peerId) => console.log('message from', peerId, data));

// Host: create a room
await engine.createRoom('my-room-123');

// Guest: join the same room
await engine.joinRoom('my-room-123');

// Once onPeerConnected fires, send data
engine.send({ type: 'chat', text: 'Hello!' });
04 / Cloudflare Mode

CloudflareWSEngine

CloudflareWSEngine swaps Firestore for a WebSocket to a Cloudflare Durable Object. Signals arrive instantly instead of through snapshot listeners. It always connects to CF_WS_URL (wss://proelectriccoder.pages.dev/api/ChatRooms); a URL passed to the constructor is ignored. Each room request carries a Firebase ID token, which the server checks.

Guest joinRoom(id, token) Durable Object ChatRooms/{id} Host createRoom(id, token) WebSocket + Firebase ID token WebSocket + Firebase ID token offer {from: guestId} offer {from: guestId} answer {to: guestId} answer {to: guestId} ICE candidates (both ways) RTCDataChannel · peer to peer The socket is only needed until this opens
Fig. 4 — Cloudflare signaling. The Durable Object forwards signals and routes answers by to.

Signals sent before the socket opens wait in an outbox, and the socket reconnects with backoff. The host keeps its socket open for new guests. A guest only needs it until its channel is open. Pass token as an async function and the engine fetches a fresh token on every reconnect.

import { CloudflareWSEngine } from '/Projects/Chat/engine.js';

const engine = new CloudflareWSEngine();
const token = () => firebase.auth().currentUser.getIdToken();   // string or async function

engine.onMessage((data, peerId) => console.log(peerId, data));
engine.onRoute(({ peerId, relayed }) => console.log(relayed ? 'TURN relay' : 'direct P2P'));

await engine.createRoom('my-room-123', token);   // host
await engine.joinRoom('my-room-123', token);     // guest

Two hooks show what the socket is doing. onSignaling reports its state, and onError reports problems the engine used to only log. After 'failed' (the built-in six backoff tries are used up), reconnectSignaling() starts over with a fresh budget. Peer does all of this for you.

engine.onSignaling((state, info) => console.log('signaling', state, info));   // connecting | open | reconnecting | failed | closed
engine.onError(({ code, error }) => console.warn(code, error));                // offer | signaling-stream | token | websocket | signal
if (!engine.reconnectSignaling()) console.log('no room to reconnect to');
05 / Direct Mode

DirectEngine

DirectEngine generates SDP strings that you exchange with the remote peer through any channel: paste them in a chat, email them, show them as QR codes. No server, no sign-in, no dependency other than a modern browser. It is a single-peer engine, so there is no createRoom and the peer id passed to callbacks is always 'remote'.

Caller DirectEngine You paste · QR · email Callee DirectEngine createOffer() → offer SDP share the offer string createAnswerFor(offer) → answer share the answer string setAnswer(answer) RTCDataChannel · peer to peer No server involved at any point
Fig. 5 — Direct mode. You carry the two SDP strings; nothing else is needed.
Slow to build, on purpose: the SDP has to contain every ICE candidate, so createOffer() and createAnswerFor() wait up to 6 seconds for gathering to finish. That includes TURN relay candidates.
import { DirectEngine } from '/Projects/Chat/engine.js';

// ── Caller side ─────────────────────────────────────────
const caller = new DirectEngine();
caller.onMessage(data => console.log('received:', data));
caller.onPeerConnected(() => console.log('connected!'));

const offerSDP = await caller.createOffer();
// Display offerSDP to user — they copy/share it to callee

// After callee sends back their answer SDP:
await caller.setAnswer(answerSDP);

// ── Callee side ─────────────────────────────────────────
const callee = new DirectEngine();
callee.onMessage(data => console.log('received:', data));

const answerSDP = await callee.createAnswerFor(offerSDP);
// Display answerSDP to user — they share it back to caller
06 / Connectivity

STUN, TURN and Route Detection

Every engine builds its RTCPeerConnection from getIceConfig(): public STUN servers to find each peer’s address, plus a free public TURN relay (Open Relay Project) that only carries traffic when no direct path exists. After connecting, monitorPC inspects the selected candidate pair and calls onRoute, so the app can show direct P2P or TURN relay in the status line.

ICE gatheringhost · srflx · relay Direct path worksSTUN-discovered addresslowest latency, no third party No direct pathstrict NAT or firewallTURN relay carries the traffic monitorPC → onRouterelayed: false → direct P2Prelayed: true → TURN relay
Fig. 6 — The route is decided by ICE, then reported with onRoute.

A brief “disconnected” state is normal when a network changes, so a peer is dropped only after 8 seconds of it (graceMs), or at once on failed or closed. A ping every 5 seconds also removes a peer whose channel has been silent for 10 seconds. Any incoming frame counts as proof of life, not only a pong, so a busy peer in a throttled background tab is not dropped. All three timings are options: heartbeatMs, timeoutMs and graceMs.

// Add your own TURN server without touching the code (checked before the built-in list)
localStorage.setItem('pec_ice_servers', JSON.stringify([
  { urls: 'turn:turn.example.com:3478', username: 'user', credential: 'secret' }
]));

// Route info, for any engine
engine.onRoute(({ peerId, relayed, local, remote }) => {
  // local / remote are candidate types: 'host' | 'srflx' | 'prflx' | 'relay'
});
Shared TURN: the built-in Open Relay credentials are public and rate-limited. Use your own TURN account for anything that matters.
07 / Groups

Group Chats — Host Relay

Groups use a star topology. Members connect only to the host. When the host’s engine is created with { relay: true } it forwards each incoming frame to every other peer before handing it to its own onMessage. Receivers filter on the message’s own to field, which is how one frame can be addressed to a single member.

Hostnew ChatEngine({ relay: true })forwards raw frames Member Asends one frame Member Bfilters on its own “to” Member Cfilters on its own “to” Member Dfilters on its own “to”
Fig. 7 — Member A sends once. The host forwards the frame to B, C and D.

The relay copies raw frames and never looks inside them, so any new message type works in groups with no host changes. It also means the host can read plain-text messages unless the chat is encrypted.

const host = new CloudflareWSEngine({ relay: true });   // also accepted by ChatEngine
08 / Reference

API Reference

Simple tier: Peer

MethodReturnsDescription
Peer.host(room, opts)Promise<Peer>Create a Peer and host room. Resolves once signaling is open.
Peer.join(room, opts)Promise<Peer>Create a Peer and join room. Resolves once connected to the host. Rejects with an Error carrying .type.
Peer.makeId()stringA random 16-character hex id.
new Peer(opts)PeerSame options as above, when you want to attach handlers before host() or join(). A Peer can be used once.
peer.host(room) · peer.join(room)Promise<Peer>The instance forms of the static helpers.
peer.send(data)numberHost: to every guest. Guest: to the host. Returns how many peers it was handed to.
peer.sendTo(peerId, data)booleanSend to one connection, found by its Peer id.
peer.getConnection(peerId)Connection | nullFind a connection by the remote Peer id.
peer.disconnect()voidLeave and tell the other side first. Safe to call more than once. destroy() is an alias.
peer.getTrace()object[]The last 200 debug entries, { t, msg }.
peer.id · room · role · openpropertiesrole is 'host' or 'guest'. open is true once the Peer has connected and until it closes.
peer.connections · connection · enginepropertiesOpen connections, the guest's link to the host, and the underlying engine.

Shared — ChatEngine and CloudflareWSEngine

MethodReturnsDescription
new Engine({ relay, heartbeatMs, timeoutMs, graceMs }) engine relay: true makes this side forward every frame to its other peers (group host). The other options tune liveness (defaults 5000, 10000, 8000 ms).
send(data) number Broadcast to all open peer channels. Accepts string, object (JSON-serialised), ArrayBuffer or Blob. Returns how many channels it was written to.
sendTo(peerId, data) boolean Send to exactly one peer. false if that peer has no open channel.
hasOpenChannel() boolean True if at least one peer channel is open.
openPeerIds() string[] Ids of the peers whose channel is open.
closePeer(peerId) void Drop one peer. Fires onPeerDisconnected.
onError(cb) void cb({ code, error }). Non-fatal problems that used to be only logged: offer, signaling-stream, token, websocket, signal.
onMessage(cb) void cb(data, peerId). Called for every incoming message.
onPeerConnected(cb) void cb(peerId). Called when a data channel opens.
onPeerDisconnected(cb) void cb(peerId). Called when a peer is lost.
onRoute(cb) void cb({ peerId, relayed, local, remote }). Direct or TURN, once connected.
onTrack(cb) void cb(stream, peerId). A remote audio or video stream arrived.
addLocalStream(peerId, stream) void Add a local media stream to one peer’s connection.
disconnect() void Close all peer connections and signaling. Safe to call more than once.

ChatEngine only

MethodReturnsDescription
init(db) void Inject a firebase.firestore() instance. Required before room methods; throws without one.
createRoom(roomId) Promise<string> Host: create the room document and answer every guest offer that appears under signals.
joinRoom(roomId) Promise<void> Guest: write an offer, apply the host’s answer and candidates, trickle your own.

CloudflareWSEngine only

MethodReturnsDescription
init() void No-op, so both signaling engines can be set up the same way.
createRoom(roomId, token) Promise<string> Host: open the signaling socket and answer guests. token is a Firebase ID token or an async function returning one.
joinRoom(roomId, token) Promise<void> Guest: send an offer through the socket and connect. Resends it if the socket reopens.
isHost boolean True after createRoom.
onSignaling(cb) void cb(state, info) for the signaling socket: connecting, open, reconnecting ({ attempt, delayMs }), failed ({ attempts }), closed.
reconnectSignaling() boolean Open the socket again with a fresh retry budget, for example after failed. false when there is no room.

DirectEngine

MethodReturnsDescription
createOffer() Promise<string> Generate the SDP offer string (JSON). Share it with the remote peer out-of-band.
createAnswerFor(offer) Promise<string> Callee: consume an offer string and return the answer string to send back.
setAnswer(answer) Promise<void> Caller: apply the answer string. Completes the handshake.
new DirectEngine({ heartbeatMs, timeoutMs, graceMs }) engine Same liveness options as the other engines.
send(data) boolean Send over the data channel. Warns and returns false if it is not open.
onMessage(cb) void cb(data, 'remote')
onPeerConnected(cb) void cb('remote')
onPeerDisconnected(cb) void cb('remote')
onRoute(cb) · onTrack(cb) · onError(cb) void Same as the shared engines, with the peer id always 'remote'.
sendTo(id, data) · hasOpenChannel() · openPeerIds() · closePeer() — Parity with the other engines, so code can swap engines. There is only one peer, so the id is ignored.
addLocalStream(stream) void Add a local media stream. There is only one peer, so no id.
disconnect() void Close the peer connection and data channel.

Module exports

ExportReturnsDescription
CF_WS_URLstringThe relay URL CloudflareWSEngine always uses.
getIceConfig()RTCConfigurationSTUN and TURN servers, with any pec_ice_servers entries first.
detectRoute(pc)Promise<object | null>{ relayed, local, remote } for the selected candidate pair, or null if unknown.
Peer · ConnectionclassesThe simple tier. See Quick Start.
ENGINE_VERSIONstringThe engine.js version, for example '1.5.0'.
monitorPC(pc, opts)voidWatch a connection: opts.onRoute(info), opts.onDead(), opts.graceMs (default 8000).
09 / Examples

Usage Examples

Collaborative code editing

engine.onMessage((msg) => {
  if (msg.type === 'edit') {
    editor.applyDelta(msg.delta);
  }
});

editor.onChange(delta => {
  engine.send({ type: 'edit', delta });
});

Sending binary data (file transfer)

// Sender
const buffer = await file.arrayBuffer();
engine.send(buffer);  // ArrayBuffer sent as binary frame

// Receiver
engine.onMessage(data => {
  if (data instanceof ArrayBuffer) {
    const blob = new Blob([data]);
    saveBlob(blob);
  }
});

The Chat App itself sends files as a file-meta message, then file-chunk messages, then file-done.

10 / Data

Data Types

The engine transparently serialises and deserialises data so you can work with native JS types.

Sent asReceived asNotes
string string Passed through as-is. A JSON parse is attempted on receive and falls back to the string.
object / array object / array Serialised with JSON.stringify, parsed on receive.
ArrayBuffer ArrayBuffer Sent as a binary WebRTC frame. No JSON serialisation.
Uint8Array / other typed arrays object (broken) Not binary-safe: they are JSON-serialised like any object. Send u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength) instead.
Blob ArrayBuffer Sent natively. The channel’s binaryType is 'arraybuffer', so it arrives as an ArrayBuffer.
number / boolean number / boolean Converted with String(), then parsed back. A string such as "42" also comes back as a number, so wrap values in an object when the type matters.
11 / Firestore

Firestore Schema

chatRooms is used only for signaling. Once connected, it is idle. The Chat App adds a second collection, chatIds, that maps a readable Chat ID to an account.

chatRooms/ (collection)
└─ {roomId}/ (document)
   ├─ createdAt: Timestamp
   ├─ host: true
   └─ signals/ (subcollection)
      └─ {guestId}/ (one document per guest)
         ├─ type: "offer"
         ├─ sdp: "<offer SDP string>"
         ├─ createdAt: Timestamp
         ├─ guestCandidates: ICECandidate[]   (written by guest, grows as ICE trickles)
         ├─ answer: "<answer SDP string>"        (written by host)
         └─ hostCandidates: ICECandidate[]    (written by host)

chatIds/ (collection, Chat App only)
└─ {chatId}/ lower-cased, e.g. google-you@gmail.com
   ├─ uid: "<Firebase UID>"
   ├─ provider: "google.com" | "github.com" | "password"
   └─ claimedAt: Timestamp
In production, add Firestore security rules to restrict who can read and write room signals. The rules for chatIds are in FIRESTORE_RULES.md.
12 / Production

Production Checklist

The demo path works on a laptop. These are the things that decide whether it keeps working for other people.

AreaWhat to do
Firestore rulesFirebase signaling needs rules for chatRooms. The repo only documents the chatIds rules, so the room rules live in your Firebase console. If you are starting fresh, the snippet below is the minimum: it only requires sign-in.
AuthPass token as an async function so reconnects get a fresh one. The Cloudflare relay verifies the Firebase ID token and answers 403 to password accounts whose email is not verified.
Room namesNeither signaling path decides who may join a room beyond requiring sign-in. Use unguessable room names (Peer.makeId() works) and check membership in your own message protocol.
TURNThe built-in Open Relay credentials are public and rate-limited. Add your own through pec_ice_servers; Peer picks it up automatically. Watch route-change to see how many links end up relayed.
Browser supportNeeds RTCPeerConnection, RTCDataChannel and ES modules. The code uses optional chaining, so the floor is roughly Chrome and Edge 80, Firefox 72 and Safari 13.1. Check Peer errors of type unavailable.
Message sizeKeep a single send under about 256 KiB and chunk anything bigger, as the Chat App does with file-meta, file-chunk and file-done. Older browsers are only safe at 16 KiB. Typed arrays must be sent as an ArrayBuffer.
Graceful exitCall peer.disconnect(), for example on pagehide. The other side then closes with a reason. Without it, a host waits for 10 seconds of silence and a guest goes through its reconnect attempts.
Sleepy tabsBrowsers throttle timers in background tabs. Since 1.5.0 any incoming frame counts as proof of life, but for apps where tabs sleep for long periods raise timeoutMs.
Stale roomsFirebase mode never deletes chatRooms or signals documents. Both carry createdAt, so add a Firestore TTL policy on it, or sweep them from a scheduled function. Cloudflare rooms leave nothing in Firestore.
ObservabilitySubscribe to error, reconnecting and route-change, and attach peer.getTrace() to bug reports.

A minimal rules block for Firebase signaling (tighten it for your own data model):

match /chatRooms/{roomId} {
  allow read, write: if request.auth != null;
  match /signals/{guestId} {
    allow read, write: if request.auth != null;
  }
}
13 / Troubleshooting

Known Failure Modes

Symptoms first. Each row names the cause the code can actually produce, and the quickest way to confirm it.

SymptomLikely causeWhat to do
join() rejects with timeout, or an engine guest waits foreverNo host is listening in that room, the room names differ, or the host's signaling is down.Check that the host got open, compare room names, and watch signaling events. The engines have no join timeout, so add your own if you use them directly.
Stuck on connecting, on some networks onlyICE cannot find a path, and the TURN relay is unreachable or rate-limited.Watch route-change. Add your own TURN server through pec_ice_servers.
conn.relayed is true when you expected directA strict NAT or firewall. A TURN server carries the traffic.Normal on some corporate and mobile networks. Latency is higher, and the shared relay can run out of capacity.
Console shows [Engine] no open channelssend() was called before any channel opened.Wait for open or onPeerConnected. conn.send() queues instead.
A peer is dropped after about 10 seconds in a background tabThe tab's timers are throttled, so its pings stop.Fixed for most cases in 1.5.0 (any frame counts). Raise timeoutMs for tabs that sleep.
Binary data arrives as an object of numbered keysA Uint8Array or DataView was sent. Only ArrayBuffer and Blob are binary-safe.Send the underlying ArrayBuffer. DeepBlue IDE's collab code does this.
The string "42" comes back as a numberString payloads are JSON-parsed on receive.Wrap values in an object: { v: "42" }.
Messages with a __peer field never arriveThat field marks the Peer layer's hello and goodbye frames, which are filtered out.Rename the field.
error of type signaling mentioning signaling-streamA Firestore listener broke: the rules deny access, or the client went offline.Check the rules and that the user is signed in.
Signaling keeps reconnecting, then failedThe Cloudflare relay refused the socket: an invalid or expired token, or an unverified password account. It answers 403, which browsers do not expose to JavaScript.Pass token as an async function, and require email verification at sign-up.
A host that lost signaling cannot be joinedIts socket is down. Guests already connected are unaffected, but new ones cannot find it.Handle disconnected and reconnected. A host that exhausts its retries emits an error.
A non-Peer host logs unknown { __peer: "hello" } framesA Peer guest introduced itself to a plain engine host.Ignore frames whose __peer is a string. After 2 seconds the guest opens anyway, under the id "host".
14 / Reference Apps

Reference Apps

Three apps in this repository run on the same engine.js. They use the advanced tier on purpose: they predate Peer and rely on relay or raw channels. Read them as worked examples of the engines.

Chat App

The widest tour: all three engines, 1:1 chats and groups with a relay: true host, a message protocol on top, and call signaling carried over the chat’s own channel.

DeepBlue IDE collab

A CloudflareWSEngine whose host relays, so guests see each other’s edits. Yjs updates travel as ArrayBuffer frames, and both sides announce on every connect so a rejoining peer catches up.

Cards game

A host that is the authority and does not relay. It deals each player a private hand with engine.sendTo(), so one player’s cards never travel to another.

Moving an app from the engines to Peer

For a new app with one host and several guests that need ids, reconnect and typed errors (lobbies, shared cursors, small games), start with Peer. The mapping from the engine calls is direct:

Engine callPeer equivalent
engine.createRoom(room, token)Peer.host(room, { token })
engine.joinRoom(room, token)Peer.join(room, { token })
engine.onMessage((data, peerId) => …)peer.on('message', ({ from, data }) => …)
engine.onPeerConnected(id => …)peer.on('connection', conn => …) on the host, await Peer.join() on a guest
engine.onPeerDisconnected(id => …)peer.on('peer-left', conn => …) on the host, conn.on('close') anywhere
engine.onRoute(info => …)peer.on('route-change', info => …)
engine.send(data) · engine.sendTo(id, data)peer.send(data) · peer.sendTo(peerId, data)
engine.disconnect()peer.disconnect()
15 / Chat App

The Chat App version 4.0.0

The app lives in /Projects/Chat/App/: plain ES modules, no bundler. It uses the engines above and adds everything a chat needs on top.

Chats

1:1 over Direct, Firebase or Cloudflare, and groups with a host relay. Readable Chat IDs: google-…, github-…, email-….

Messages

Replies, reactions, edit and delete for everyone, and polls where votes can be changed and are visible.

Find things

In-chat search with highlights, pinned messages, personal stars, and a library of media, files and links.

Voice and files

Voice messages with a waveform, chunked file transfer with previews, and link previews through an Open Graph function.

Calls

1:1 voice, video and screen sharing, plus group calls. Call signaling travels over the chat’s own channel.

Awareness

Delivered and read ticks, “Seen by” in groups, typing indicators, browser notifications, per-chat mute.

Privacy

Optional password-based AES-GCM encryption of message content, and disappearing messages: 5 minutes to 7 days, removed on every device.

Backup

Optional Google Drive backup and restore of chats, with expired messages never included.

Message protocol

Everything the app sends is one JSON object with a type. The host relay forwards unknown types untouched, so new ones work in groups automatically.

typePurpose
chatA text message. Carries a shared id, the author id aid, an optional reply and the chat’s ttl.
msg-delivered · msg-readReceipts for a message id.
msg-react · msg-pin · msg-edit · msg-deleteChanges to an existing message. Only its author may edit or delete.
poll · poll-vote · poll-closeCreate, vote on (and change a vote on) and close a poll.
chat-ttlSet the disappearing-message timer: 0, 300, 3600, 86400 or 604800 seconds.
file-meta · file-chunk · file-doneA file or voice message, sent in pieces.
typing · typing-stopTyping indicator.
call-logCall card, with the call’s SDP and ICE in its meta.
gc-*Group call invite, accept, offer, answer, ICE and end.
handshake · group-members · display-nameNames, avatars and the member list.
Limits worth knowing: edits, deletes and timers only reach peers who are online. In groups the author id is asserted by the sender’s client. Disappearing messages cannot stop screenshots.