A comprehensive WebRTC walkthrough

Carles Capellas
9 min readJul 12, 2023

WebRTC allows for real-time communication between two peers using only the browser’s built-in functionalities, with no need for a communications server. That’s AWESOME. But turns out that the browser API is complex, and I find the official samples repository a bit confusing. Here is an attempt to provide a clearer example.

The idea is to establish a connection between two browsers (or two tabs of the same browser) running the same Javascript code. The browsers, or peers, can be either in the same device or in different devices and each of them will be able to act both as the starter or the receiver of a connection.

Connection overview

Before diving into the code it’s worth understanding the steps involved in establishing a WebRTC connection. Let’s have a look at the following simplified connection diagram (based on the WebRTC Connectivity documentation), which reflects the basic operations the two peers need to execute:

WebRTC connection diagram
  • Initialize. Both peers create a new connection object.
  • Media. Peer A adds media to the connection (i.e. data channels and/or stream tracks).
  • Offer creation. Peer A creates an offer (i.e. session description) and sets it as the local description. The latter will generate several ICE candidates.

--

--

Carles Capellas
Carles Capellas

Written by Carles Capellas

Always up for sport, somewhat obsessive about order and, over all things, enthusiastic about coding