← All Insights

ReactJS Peer to Peer Communication with PeerJS

WebRTC enables direct browser-to-browser communication without routing data through a server. PeerJS wraps WebRTC into a clean API, handling the signalling complexity so you can focus on the application logic. You still need a lightweight broker server to establish the initial connection, but once peers are connected, all data flows directly between them.


How PeerJS Works

Each peer registers with a broker server and receives a unique peer ID. When peer A wants to connect to peer B, it passes peer B's ID to the broker, which facilitates the WebRTC handshake. After the connection is established, all data is transferred directly between the two peers — the broker server is no longer involved.


Step 1: Set Up the Broker Server

Install the peer package and create a simple Node.js server:

npm install peer
// server.js
const { PeerServer } = require('peer');

const peerServer = PeerServer({ port: 9000, path: '/peerjs' });

peerServer.on('connection', client => {
  console.log('Peer connected:', client.getId());
});

peerServer.on('disconnect', client => {
  console.log('Peer disconnected:', client.getId());
});

Start it with node server.js. This server only handles signalling — no peer-to-peer data passes through it.


Step 2: Connect from React

Install PeerJS in your React project:

npm install peerjs

Initialise the peer connection in componentDidMount (or a useEffect hook):

import Peer from 'peerjs';

componentDidMount() {
  this.peer = new Peer(undefined, {
    host: 'localhost',
    port: 9000,
    path: '/peerjs',
  });

  this.peer.on('open', id => {
    console.log('My peer ID:', id);
    this.setState({ myId: id });
  });

  this.peer.on('connection', conn => {
    conn.on('data', data => {
      console.log('Received:', data);
      this.setState(prev => ({
        messages: [...prev.messages, data],
      }));
    });
  });

  this.peer.on('error', err => {
    console.error('Peer error:', err);
  });
}

Step 3: Connect to Another Peer and Send Data

connectAndSend = (remotePeerId, message) => {
  const conn = this.peer.connect(remotePeerId);

  conn.on('open', () => {
    conn.send(message);
  });
};

Pass the remote peer's ID (shared out-of-band, e.g. via a URL or a separate channel) and the message. Once the connection opens, data is sent directly.


Production Considerations

In development, PeerJS uses its default cloud servers for ICE (Interactive Connectivity Establishment). In production, you should run your own STUN and TURN servers to handle NAT traversal reliably. A common choice is coturn:

this.peer = new Peer(undefined, {
  host: 'your-broker.example.com',
  port: 9000,
  path: '/peerjs',
  config: {
    iceServers: [
      { urls: 'stun:stun.example.com:3478' },
      {
        urls: 'turn:turn.example.com:3478',
        username: 'user',
        credential: 'pass',
      },
    ],
  },
});

Conclusion

PeerJS makes peer-to-peer communication in React approachable. The broker server footprint is minimal, and once peers are connected the data path is entirely direct. For use cases like collaborative editing, live chat, or file sharing between two known parties, this is a lightweight and effective architecture.