Skip to content

Quick start ​

A page that joins a room, sends messages to everyone in it, and keeps records that outlive the page: about twenty lines with PeerPigeon.

Install ​

bash
npm install peerpigeon

PeerPigeon is an ES module for browsers and Node. It brings freertc (the relay client) and UnSea (the cryptography) with it.

Join a room ​

js
import { PeerPigeonNode } from 'peerpigeon'

const node = new PeerPigeonNode({
  networkId: 'my-app',              // your app's own namespace
  sessionId: 'lobby',               // the room
  signalingServer: 'wss://peer.ooo/ws',
  automaticSignalingServer: true,   // let PeerPigeon pick the room's relay
  storage: { replicate: ['notes/'] },
})

node.on('peerConnected', (peerId) => console.log('linked to', peerId))
node.on('message', (m) => {
  if (!m.local) console.log(m.kind, 'from', m.fromPeerId, m.data)
})

await node.start()

Peers find each other only when both networkId and sessionId match. The first relay URL is a starting point: with automaticSignalingServer, PeerPigeon reads the relay registry and joins the relays closest to the room, so a room's peers gather on a few relays (how it chooses).

Send ​

js
node.broadcast({ text: 'hello, everyone' })      // gossip to the whole room
node.sendDirect(peerId, { text: 'just you' })    // one peer, routed across the mesh

broadcastEncrypted and sendEncryptedDirect do the same with the room's encryption (on by default: pass crypto: false to the node to leave it out).

Keep records ​

js
await node.storage.put('public', 'notes/1', { text: 'still here tomorrow' })
const record = await node.storage.get('public', 'notes/1')

node.storage.subscribe((change) => {
  console.log(change.op, change.key, change.record?.value)
})

Every change is signed with the node's keys and synced to the room. With replicate: ['notes/'], this node keeps everything under notes/, and a peer that joins later is sent all of it at once. When the room's storage servers are up, records also go to them, so they are there when no peer is online. Storage explains the spaces and who may write what.

Try it locally ​

Run a relay on your own machine and point the page at it:

bash
git clone https://github.com/draeder/freertc && cd freertc && npm install
FREERTC_FEDERATION=off node scripts/node-relay.mjs     # ws://127.0.0.1:8788/ws

Then use signalingServer: 'ws://127.0.0.1:8788/ws'. With federation off, nothing reaches the public relays: good for tests with many peers.

peer.ooo · peer to peer on PeerPigeon