What Is WebRTC? A Complete Beginner's Guide
Learn how WebRTC enables browser-to-browser peer-to-peer file sharing. Discover SDP, ICE candidates, STUN/TURN servers, and data channels.
What Is WebRTC? A Complete Beginner's Guide
Historically, real-time web communications required intermediate servers to process and relay every packet of video, audio, or file data. This architecture added server latency, inflated hosting bills, and introduced security concerns. In 2011, Google open-sourced WebRTC (Web Real-Time Communication), a standard that allows browsers to communicate directly peer-to-peer.
This guide explains WebRTC from scratch, focusing on how browser-to-browser file transfers work. You will learn the roles of SDP, ICE candidates, and STUN/TURN servers. We provide text-based routing diagrams and a JavaScript code snippet showing how to negotiate a peer connection.
---
Table of Contents 1. [What is WebRTC?](#what-is-webrtc) 2. [The Core WebRTC APIs](#the-core-webrtc-apis) 3. [The Problem: NATs and Firewalls](#the-problem-nats-and-firewalls) 4. [The Signaling Phase and SDP Handshake](#the-signaling-phase-and-sdp-handshake) 5. [NAT Traversal: STUN and TURN](#nat-traversal-stun-and-turn) 6. [Interactive Connectivity Establishment (ICE)](#interactive-connectivity-establishment-ice) 7. [The Architecture: P2P vs Relayed Routing](#the-architecture-p2p-vs-relayed-routing) 8. [Developer Example: Establishing a Connection Handshake](#developer-example-establishing-a-connection-handshake) 9. [WebRTC Connection Performance Table](#webrtc-connection-performance-table) 10. [Best Practices Checklist](#best-practices-checklist) 11. [Frequently Asked Questions](#frequently-asked-questions) 12. [Conclusion](#conclusion)
---
What is WebRTC?
WebRTC is a collection of standards, protocols, and JavaScript APIs that allow browsers to establish direct peer-to-peer (P2P) connections. This technology is built directly into all major browsers (Chrome, Firefox, Safari, Edge), meaning users can share media streams or files without downloading external plugins or software.
---
The Core WebRTC APIs
WebRTC is divided into three primary JavaScript APIs:
- `MediaStream` (getUserMedia): Captures audio and video streams from the user's camera and microphone.
- `RTCPeerConnection`: Manages the connection lifecycle, optimizes bandwidth on the fly, handles encryption handshakes, and coordinates network details.
- `RTCDataChannel`: Allows browsers to transfer arbitrary binary data (like files or database snapshots) directly over the peer connection.
For file sharing apps, the `RTCDataChannel` is the core engine, as it provides low-latency, secure datagram pipes.
---
The Problem: NATs and Firewalls
In an ideal world, establishing a peer connection would be simple: Browser A would call Browser B's public IP address. However, NAT (Network Address Translation) and firewalls block this direct path: - NAT: Routers use NAT to map multiple private IP addresses (like `192.168.1.15`) inside a home or office to a single shared public IP address. - Firewalls: Security systems automatically block unsolicited incoming connection packets.
To traverse firewalls, WebRTC uses a structured lookup process.
---
The Signaling Phase and SDP Handshake
To locate each other, browsers must perform an initial handshake. This process is called signaling.
The signaling server acts as a temporary routing intermediary. It does not touch or process your files; it only exchanges connection metadata: - SDP (Session Description Protocol): The sender generates an SDP "offer" containing its local connection settings (codecs, encryption protocols, transport settings). The receiver answers with its own SDP description. - Handshake Exchange: The signaling server routes the offer and answer between the browsers, allowing them to establish a common communication layout.
---
NAT Traversal: STUN and TURN
To find public-facing paths, browsers query NAT helper servers:
- STUN (Session Traversal Utilities for NAT): A STUN server is a public node that returns the browser's public IP address and port mapping.
- TURN (Traversal Using Relays around NAT): If firewalls block the direct connection (Symmetric NAT), the browsers fall back to a TURN server, which acts as a relay router for the encrypted packets.
---
Interactive Connectivity Establishment (ICE)
The process of discovering, gathering, and testing network paths is called Interactive Connectivity Establishment (ICE).
During connection setup, WebRTC gathers multiple ICE candidates (local LAN paths, public STUN mappings, and TURN relays). The browsers exchange these candidates and test each path sequentially, selecting the fastest connection layout that successfully passes firewall checks.
---
The Architecture: P2P vs Relayed Routing
The following text diagrams outline how data flows during WebRTC sessions.
Direct P2P Connection (STUN Discovered) ``` [ Browser A ] <========== (Direct Encrypted Link) ==========> [ Browser B ] | | +-------> [ STUN Server ] (Discovers Public IPs) <------------+ ```
Relayed Connection (TURN Fallback) ``` [ Browser A ] <---> [ TURN Relay Server ] <---> [ Browser B ] (Relays Encrypted Payload Packets) ```
---
Developer Example: Establishing a Connection Handshake
The following script illustrates how to initialize an `RTCPeerConnection`, set up local and remote SDP offers, and track ICE candidates:
```javascript // Configuration with public STUN servers for NAT lookup const rtcConfig = { iceServers: [{ urls: "stun:stun.l.google.com:19302" }] };
const peerConnection = new RTCPeerConnection(rtcConfig);
// Handle ICE candidate discovery peerConnection.onicecandidate = (event) => { if (event.candidate) { // Send ICE candidate to signaling server console.log("Local ICE Candidate discovered:", event.candidate.candidate); sendCandidateToSignalingServer(event.candidate); } };
// Create local offer (Sender side) async function startConnection() { const dataChannel = peerConnection.createDataChannel("file-transfer"); dataChannel.onopen = () => console.log("Data channel established."); dataChannel.onmessage = (event) => console.log("Data received:", event.data);
const offer = await peerConnection.createOffer(); await peerConnection.setLocalDescription(offer); // Send offer to the receiver via signaling server sendOfferToSignalingServer(offer); }
// Receive offer and generate answer (Receiver side) async function handleIncomingOffer(offer) { await peerConnection.setRemoteDescription(new RTCSessionDescription(offer)); const answer = await peerConnection.createAnswer(); await peerConnection.setLocalDescription(answer); // Send answer back to sender via signaling server sendAnswerToSignalingServer(answer); } ```
---
WebRTC Connection Performance Table
| Connection Profile | Routing Route | Latency | Bandwidth Cost | Security | | :--- | :--- | :--- | :--- | :--- | | Local Host | Local LAN (Wi-Fi/Ethernet) | < 2ms | None (Free local data) | High (Local subnet only) | | Reflexive (STUN) | Public WAN (Direct P2P Link) | Low (Direct routing) | None (Public STUN is free) | High (DTLS Encrypted) | | Relayed (TURN) | Remote Relay Server | Medium to High | High (Relay server costs) | High (Relayed encrypted data) |
---
Best Practices Checklist
Ensure your WebRTC implementations remain reliable by checking these parameters:
- [ ] Implement Trickle ICE: Send ICE candidates to the remote peer as soon as they are gathered to decrease connection establishment time.
- [ ] Configure TURN Servers: Always provide fallback TURN servers to ensure connections succeed for users behind Symmetric corporate NATs.
- [ ] Handle State Changes: Monitor `connectionState` and `iceConnectionState` to identify and resolve dropped connections.
- [ ] Manage Backpressure: Check the data channel's `bufferedAmount` to prevent browser memory bloat when sending large files.
---
Frequently Asked Questions
What makes WebRTC peer-to-peer connections secure? WebRTC mandates DTLS (Datagram Transport Layer Security) encryption for all data streams. This guarantees that your data is encrypted at the local sandbox level and cannot be read by intermediate routers.
Why do I need a signaling server if WebRTC is peer-to-peer? Browsers cannot discover each other automatically due to firewalls. The signaling server is required to route connection metadata (SDP offers/answers and ICE candidates) so the peers can locate each other.
What is the difference between STUN and TURN? STUN servers discover your public IP address and port mapping. TURN servers act as relay nodes, routing traffic if direct P2P connections are blocked by firewalls.
Can WebRTC work without an internet connection? Yes. If both devices are on the same local area network (LAN), WebRTC can resolve local ICE candidates and transfer files locally without accessing the public internet.
What protocol is used inside the RTCDataChannel? The `RTCDataChannel` uses the SCTP (Stream Control Transmission Protocol) encapsulated over DTLS and UDP to provide fast, reliable, and ordered data transmission.
Does WebRTC work on mobile devices? Yes, WebRTC is natively supported on mobile browsers (Safari for iOS, Chrome/Firefox for Android) and through native iOS and Android SDK libraries.
Are TURN servers expensive to maintain? Yes. Unlike STUN servers which only handle small metadata requests, TURN servers relay the entire payload, consuming significant server bandwidth.
---
Conclusion
WebRTC has redefined browser communication by shifting from client-server architectures to direct peer-to-peer mesh networks. By utilizing signaling servers for connection discovery and STUN/TURN for firewall traversal, it establishes secure, low-latency datagram channels directly between browsers.
If you are looking for a simple, browser-based way to transfer files securely without creating an account or storing data in the cloud, CoShareX offers direct peer-to-peer sharing. By establishing an encrypted WebRTC data channel, it streams your files directly between browsers, keeping the workflow lightweight and secure.