AI Workshop: learn to build apps with AI →
Other JavaScript Libraries: PeerJS

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


PeerJS

PeerJS is an awesome library that makes WebRTC easier. Working with WebRTC directly can be complex, but PeerJS simplifies peer-to-peer real-time communication.

How it works

First, you need a backend to allow 2 clients to synchronize before they are able to directly talk to each other.

In a folder, initialize an npm project, install PeerJS, and run the server:

npm init -y
npm install peerjs
npx peerjs --port 9000

Run npx peerjs --help to see all the options you can use.

This is your backend!

Creating a receiver

Now we can create a simple application. First, the receiver, which connects to our PeerJS server and listens for data.

Include the PeerJS client:

<script src="https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js"></script>

Then initialize the Peer object. The connection event is called when another peer connects to us. When we receive some data, the data event is called with the payload:

const peer = new Peer('receiver', { host: 'localhost', port: 9000, path: '/' })

peer.on('connection', (conn) => {
  conn.on('data', (data) => {
    console.log(data);
  })
})

Creating a sender

Now create the sender that will connect and send a message to the receiver.

We initialize the Peer object, then ask the peer to connect to the receiver peer. Once the connection is established, the open event fires, and we can call send():

const peer = new Peer('sender', { host: 'localhost', port: 9000, path: '/' })

const conn = peer.connect('receiver')

conn.on('open', () => {
  conn.send('hi!')
})

Testing it

First open the receiver page, then open the sender page. The receiver gets the message directly from the sender, not from a centralized resource.

The server part is only needed to exchange information so the 2 peers can connect. After that, it no longer interferes.

Use cases

PeerJS is great for:

  • Video/audio chat applications
  • File sharing
  • Real-time multiplayer games
  • Collaborative editing tools
  • Any application where you want direct peer-to-peer communication

Lessons in this unit:

0: Introduction
1: jQuery
2: Axios
3: Moment.js
4: SWR
5: XState
6: ▶︎ PeerJS