Leveraging WebRTC and PeerJS: Building Real-time Communication Web Apps published 10/5/2023 | 4 min read

This article was ai-generated by GPT-4 (including the image by Dall.E)!
Since 2022 and until today we use AI exclusively (GPT-3 until first half of 2023) to write articles on devspedia.com!

What is WebRTC and Why is It Valuable?

Web Real-Time Communications (WebRTC) is an open-source project offering web browsers and mobile apps real-time communication (RTC) capabilities via simple APIs. It allows audio and video communication to work inside web pages by allowing direct peer-to-peer communication, eliminating the need to install plugins or download native apps.

WebRTC is valuable for creating chat applications, video conferencing tools, multiplayer online games, and similar real-time applications, while maintaining high-level security, quality, and device interoperability.

  
// Simple WebRTC example
const localVideo = document.querySelector('video');

navigator.mediaDevices.getUserMedia({video: true, audio: false})
.then((stream) => {
localVideo.srcObject = stream;
})
.catch((error) => {
console.log('getUserMedia() error: ', error);
});



What is PeerJS and How Does It Connect with WebRTC?

PeerJS provides a simple API for WebRTC and builds an abstraction layer that masks the complexities of browser differences and the underlying WebRTC and DataChannel APIs. PeerJS library make it significantly easier to establish a peer-to-peer connection, without losing WebRTC's powerful features.

The connection to the PeerJS server helps with peer discovery and setting up connections. Once the WebRTC connection has been established, though, the server step out of the process so that your data is flowing directly from one client to another.

Building our First WebRTC App Using PeerJS

Let’s create a basic one-to-one video chat application using WebRTC and PeerJS. For this example, we'll need Node.js installed and a basic understanding of JavaScript.

  1. Start by creating a new Node.js project and install the necessary packages:
  
$ mkdir webrtc-peerjs-communication && cd webrtc-peerjs-communication
$ npm init -y
$ npm install express peer

  1. Create an index.html file for client-side implementation and a server.js file for server-side implementation in the root directory of the project.

  2. Inside the server.js file, write the following code:

  
const express = require('express');
const { ExpressPeerServer } = require('peer');

const app = express();
const server = app.listen(3000);

const peerServer = ExpressPeerServer(server, {
    debug: true,
    path: '/'
});
app.use('/peerjs', peerServer);

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});
console.log('Server running...');



  1. For the index.html file, we will need to implement video elements for user and partner video. Also, the PeerJS library needs to be added.
  

<!-- Add the PeerJS library -->
<script src="/peerjs/peerjs.min.js"></script>

<video id="userVideo" autoplay muted></video>
<video id="partnerVideo" autoplay></video>

<button id="callButton">Call Partner</button>

<script src="main.js"></script>


  1. Then, create a main.js file in the root directory and add the following code to establish connection and start a call.
  

// Create a new peer with our PeerJS server settings.
const myPeer = new Peer(undefined, { host: '/', port: 3000, path: '/peerjs' });

// Get our video elements from the page.
const userVideo = document.querySelector('#userVideo');
const partnerVideo = document.querySelector('#partnerVideo');
const callButton = document.querySelector('#callButton');

// Get the stream from our webcam and microphone.
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then((userStream) => {
  userVideo.srcObject = userStream;
  
  // Listen for call event
  myPeer.on('call', (incomingCall) => {
    incomingCall.answer(userStream);
    incomingCall.on('stream', (partnerStream) => {
      partnerVideo.srcObject = partnerStream;
    });
  });

  // Add an event listener to our call button.
  callButton.addEventListener('click', () => {
    // Make a call to our partner peer.
    const outgoingCall = myPeer.call('partner-id', userStream);
    outgoingCall.on('stream', (partnerStream) => {
      partnerVideo.srcObject = partnerStream;
    });
  });
});


  1. To start the server, run node server.js in your terminal and open http://localhost:3000 in two different web browser tabs.

There you have it, a simple one-to-one video chat application using WebRTC and PeerJS.

In this guide, we've just scratched the surface of what's possible with WebRTC and PeerJS. Investing time into mastering these technologies can enable you to create advanced real-time web applications to enrich your users' experiences.



You may also like reading: