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.
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.
Peer. The engines underneath are public and unchanged.| Engine | Signaling | Needs | Use it for |
|---|---|---|---|
| ChatEngine | Firestore documents | Firebase project | Rooms and inboxes where peers join at different times |
| CloudflareWSEngine | WebSocket to a Durable Object | Firebase ID token | Live signaling with no Firestore round trips; used for the app’s Cloudflare rooms and groups |
| DirectEngine | You copy and paste SDP | Nothing | Offline or serverless use |
Simple: Peer | Advanced: engines | |
|---|---|---|
| Set up a room | Peer.host(room, opts) / Peer.join(room, opts) | new Engine(), init, callbacks, createRoom / joinRoom |
| Who is on the other end | conn.peer (a stable id you choose) and conn.metadata | A throwaway engine id per link |
| Reconnect | Automatic, with backoff and a retry budget | You rebuild the engine and rejoin |
| Timeouts and errors | Typed errors: auth, signaling, timeout, connection-lost | onError and onSignaling hooks; no join timeout |
| Debugging | debug: true and peer.getTrace() | Console logs |
| Group relay, media tracks, Direct mode | Not covered. Reach the engine with peer.engine | Full control |
| Topology | Star: guests talk to the host, the host talks to all guests | Star, with optional relay: true host |
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() and join() to a clean exit or a reconnect.| Option | Default | Description |
|---|---|---|
| signaling | 'cloudflare' | 'cloudflare' needs token. 'firebase' needs db. |
| token | none | A Firebase ID token, or an async function returning one. A function is called again on every signaling reconnect, so the token never goes stale. |
| db | none | firebase.firestore(), when signaling is 'firebase'. |
| id | random | Your Peer id. The other side sees it as conn.peer. Pick something stable, such as a Chat ID. |
| metadata | null | Any 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. |
| connectTimeoutMs | 20000 | How long a guest waits for the host to answer, and how long a host waits for signaling to open. |
| heartbeatMs · timeoutMs · graceMs | 5000 · 10000 · 8000 | Ping interval, silence before a peer is dropped, and the time a disconnected link gets to recover. |
| debug | false | true logs to console.debug. A function receives each { t, msg } entry. peer.getTrace() always holds the last 200. |
| createEngine | none | (engineOptions) => engine. Plug in your own signaling. The object must implement the shared engine interface. |
| Event | Payload | When |
|---|---|---|
| open | id | Host: signaling is open. Guest: connected to the host. Fires once. |
| connection | conn | Host: a guest connected and the two sides have swapped ids. |
| message | { from, data, connection } | Any incoming data, from any connection. |
| peer-left | conn | Host: 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'. |
| reconnected | none | Guest: the link is back. Host: signaling is back. |
| disconnected | none | Host: 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. |
| error | Error with .type | See the error types below. |
| close | { reason } | The Peer is finished: 'local', 'host-closed', 'lost' or 'error'. |
A host gets one Connection per guest. A guest has one, to the host, at peer.connection.
| Member | Returns | Description |
|---|---|---|
| conn.peer | string | The remote Peer id (their id option). Falls back to "host" or the engine id if the remote is not a Peer. |
| conn.metadata | any | What the remote passed as metadata. |
| conn.open | boolean | True while you can send. |
| conn.relayed | boolean | null | true when a TURN relay carries the link, false when it is direct, null until known. |
| conn.send(data) | boolean | True 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() | void | Host: kick this guest. Guest: the same as peer.disconnect(). |
| conn.channel · conn.pc | object | null | Escape hatches to the RTCDataChannel and RTCPeerConnection. |
| events | 'open' (again after a reconnect), 'data', 'close', 'route', 'reconnecting'. |
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.
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.type | Meaning |
|---|---|
| auth | No token, or the token function threw. A missing token is thrown by host() and join() before anything connects. |
| signaling | The signaling server is unreachable, or a Firestore stream broke. |
| timeout | The host did not answer within connectTimeoutMs, or signaling did not open in time. |
| connection-lost | A guest lost the host and used up its retries. |
| unavailable | No WebRTC in this browser, no room name, or a Peer that was already used. A Peer is single-use: make a new one. |
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.
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.
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.
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!' });
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.
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');
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'.
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
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.
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'
});
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.
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
| Method | Returns | Description |
|---|---|---|
| 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() | string | A random 16-character hex id. |
| new Peer(opts) | Peer | Same 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) | number | Host: to every guest. Guest: to the host. Returns how many peers it was handed to. |
| peer.sendTo(peerId, data) | boolean | Send to one connection, found by its Peer id. |
| peer.getConnection(peerId) | Connection | null | Find a connection by the remote Peer id. |
| peer.disconnect() | void | Leave 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 · open | properties | role is 'host' or 'guest'. open is true once the Peer has connected and until it closes. |
| peer.connections · connection · engine | properties | Open connections, the guest's link to the host, and the underlying engine. |
| Method | Returns | Description |
|---|---|---|
| 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. |
| Method | Returns | Description |
|---|---|---|
| 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. |
| Method | Returns | Description |
|---|---|---|
| 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. |
| Method | Returns | Description |
|---|---|---|
| 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. |
| Export | Returns | Description |
|---|---|---|
| CF_WS_URL | string | The relay URL CloudflareWSEngine always uses. |
| getIceConfig() | RTCConfiguration | STUN 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 · Connection | classes | The simple tier. See Quick Start. |
| ENGINE_VERSION | string | The engine.js version, for example '1.5.0'. |
| monitorPC(pc, opts) | void | Watch a connection: opts.onRoute(info), opts.onDead(), opts.graceMs (default 8000). |
engine.onMessage((msg) => {
if (msg.type === 'edit') {
editor.applyDelta(msg.delta);
}
});
editor.onChange(delta => {
engine.send({ type: 'edit', delta });
});
// 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.
The engine transparently serialises and deserialises data so you can work with native JS types.
| Sent as | Received as | Notes |
|---|---|---|
| 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. |
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
chatIds are in
FIRESTORE_RULES.md.
The demo path works on a laptop. These are the things that decide whether it keeps working for other people.
| Area | What to do |
|---|---|
| Firestore rules | Firebase 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. |
| Auth | Pass 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 names | Neither 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. |
| TURN | The 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 support | Needs 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 size | Keep 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 exit | Call 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 tabs | Browsers 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 rooms | Firebase 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. |
| Observability | Subscribe 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;
}
} Symptoms first. Each row names the cause the code can actually produce, and the quickest way to confirm it.
| Symptom | Likely cause | What to do |
|---|---|---|
join() rejects with timeout, or an engine guest waits forever | No 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 only | ICE 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 direct | A 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 channels | send() 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 tab | The 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 keys | A 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 number | String payloads are JSON-parsed on receive. | Wrap values in an object: { v: "42" }. |
Messages with a __peer field never arrive | That field marks the Peer layer's hello and goodbye frames, which are filtered out. | Rename the field. |
error of type signaling mentioning signaling-stream | A 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 failed | The 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 joined | Its 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" } frames | A 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". |
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.
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.
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.
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.
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 call | Peer 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() |
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.
1:1 over Direct, Firebase or Cloudflare, and groups with a host relay. Readable Chat IDs: google-…, github-…, email-….
Replies, reactions, edit and delete for everyone, and polls where votes can be changed and are visible.
In-chat search with highlights, pinned messages, personal stars, and a library of media, files and links.
Voice messages with a waveform, chunked file transfer with previews, and link previews through an Open Graph function.
1:1 voice, video and screen sharing, plus group calls. Call signaling travels over the chat’s own channel.
Delivered and read ticks, “Seen by” in groups, typing indicators, browser notifications, per-chat mute.
Optional password-based AES-GCM encryption of message content, and disappearing messages: 5 minutes to 7 days, removed on every device.
Optional Google Drive backup and restore of chats, with expired messages never included.
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.
| type | Purpose |
|---|---|
| chat | A text message. Carries a shared id, the author id aid, an optional reply and the chat’s ttl. |
| msg-delivered · msg-read | Receipts for a message id. |
| msg-react · msg-pin · msg-edit · msg-delete | Changes to an existing message. Only its author may edit or delete. |
| poll · poll-vote · poll-close | Create, vote on (and change a vote on) and close a poll. |
| chat-ttl | Set the disappearing-message timer: 0, 300, 3600, 86400 or 604800 seconds. |
| file-meta · file-chunk · file-done | A file or voice message, sent in pieces. |
| typing · typing-stop | Typing indicator. |
| call-log | Call 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-name | Names, avatars and the member list. |