A JavaScript library that acts as a wrapper around WebRTC

Implementing point-to-point communication is a challenging task. But if you know the right tools, you can make it easier.

So in this article, I’ll talk about PeerJS, a JavaScript library that acts as a wrapper around WebRTC, making it easier to implement point-to-point communication in Web applications.

How does PeerJS simplify WebRTC?

WebRTC is the standard used by many developers when it comes to real-time P2P communications in web applications. However, it also has the following complications.

  • If you use pure WebRTC, first of all, you define a STUN (Session Traversal Utilities for NAT) server, Generate ICE (Interactive Connectivity Establishment) candidates for each peer participating in the communication.
  • You will then need to use your server to store the details of these ICE candidates.
  • Finally, you need to implement WebSockets to handle real-time updates.

Even if you haven’t been exposed to WebRTC before; I’m sure you sense the complexity of its implementation. But, don’t worry, PeerJS is here to help.

With PeerJS, we don’t have to worry about creating STUNs, ICE candidates, or servers. We can even avoid implementing WebSockets.

PeerJs provides a complete, configurable point-to-point connection API and a server called PeerServer to facilitate the establishment of connections between PeerJs clients.

So, let’s take a look at how to use PeerJS to create a simple chat application.

Set up your first chat room with PeerJS and React

The first step –Install PeerJS

First, we need to install the PeerJS library as a node module in your project and make the Peer library a global dependency.

// Installing PeerJS
Copy the code
// Installing Peer
Copy the code

** Note: ** The PeerJS library is used to start PeerServer locally. You can also use the PeerServer cloud instance.

Step 2 – Implement the chat room

Now, let’s move over to our React application and get started by initializing the chat component’s state.

In this state, we will process our ID, companion ID, chat message, and an instance of a companion object.

state = {
Copy the code

We then need to create a Peer instance by defining the hostname, port, and path to manage our P2P connection. We will use this example throughout the communication.

const peer = new Peer('', {
Copy the code

Tip: You can use your own ID as the first parameter, or leave it undefined and let PeerServer generate a random ID. If you use const peer = new peer (); You will be connected to the PeerServer cloud.

Peer instances have several ways to handle communication between peers. Peer-. on is used to listen for peer events and is useful when receiving calls from remote peers.

After successfully connecting to PeerServer, the Open event will be emitted and we will use this event to update myId and the status of the peer.

peer.on('open', (id) => {
Copy the code
this.setState({
Copy the code

We then need to listen for the connection of the remote peer using connection events, whose callbacks we can use to grab the messages sent by the remote peer.

peer.on('connection', (conn) => {
Copy the code
      this.setState({
Copy the code
   });
Copy the code

Now we have all the functionality to receive messages. As a final step, let’s create a method to send the message.

The peer. Connect method allows us to connect to a peer by specifying the peer ID. It then returns a DataConnection object that can be used to send message data to the peer.

send = () => {
Copy the code
  conn.on('open', () => {
Copy the code
    const msgObj = {
Copy the code
   conn.send(msgObj);
Copy the code
    this.setState({
Copy the code
  });
Copy the code

Step 3 – Video chat implementation

Now, let’s modify our chat room to send video messages. Implementing it is similar to what we discussed in the previous step. We can listen for calls from a remote peer using the call event in the peer-. on method. It provides a callback object called MediaConnection, and the receiver’s video and audio streams are provided to the reply method of the MediaConnection object.

peer.on('call', (call) => {
Copy the code
var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
Copy the code
getUserMedia({ video: true, audio: true }, (stream) => {
Copy the code
  this.myVideo.srcObject = stream;
Copy the code
  call.on('stream', (remoteStream) => {
Copy the code
}, err => { console.log('Error!') });
Copy the code

Now let’s make a video call from our terminal to the peer. This method is similar to answering a telephone. We need to use the invocation method of the initial peer instance and provide the peer ID and the video stream as parameters.

The calling method returns a MediaConnection object that we can use to access the peer’s data stream.

videoCall = () => {
Copy the code
var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
Copy the code
getUserMedia({ video: true, audio: true }, (stream) => {
Copy the code
  this.myVideo.srcObject = stream;
Copy the code
  const call = this.state.peer.call(this.state.friendId, stream);
Copy the code
  call.on('stream', (remoteStream) => {
Copy the code

Step 4 — Finalize things

Finally, it was time to add some JSX to render our chat room. Let’s add two input fields for companion ID and chat message. We will use the REF attribute to access the video element.

return (
Copy the code
    <label>Friend ID:</label>
Copy the code
<br />
Copy the code
    <label>Message:</label>
Copy the code
    <button onClick={this.send}>Send</button>
Copy the code

Here it is! Now we’re ready for a quick video chat. The final implementation will look like this, and you can find the full code in my GitHub repository.

** Note: ** Some browsers (especially mobile browsers) may not allow access to the camera and microphone without an HTTPS connection. You can follow this article to establish a local HTTPS connection through several steps.

Build and share React components with Bit

Bit is an extensible tool that allows you to create _ true _ modular applications from _ independently written, versioed, and maintained components.

Use it to build modular applications and design systems, write and deliver micro-frontend, or share components between applications.

A separate source control and shared “card” component. On the right is => its dependency graph, automatically generated by Bit.

Bit: A platform for modular networks

The last word

Web RTC is a browser standard for real-time point-to-point communication. But with STUN servers, ICE candidates, SDP, and WebSockets involved, implementing WebRTC is a little more complicated.

PeerJS simplifies the process by acting as a wrapper for WebRTC and gives us simpler events and working methods.

So, I invite you to give PeerJS a try and let me know what you think in the comments section.

Thanks for reading! !