# RTCPeerConnection

> The `RTCPeerConnection` JS object represents a WebRTC connection between the local device and a remote peer.

## How does RTCPeerConnection work?

The main WebRTC object that negotiates the connection, sends and receives media tracks and data channels, and manages ICE. Created with a list of STUN and TURN servers and controlled through offers and answers.

- Topic: Media & Audio
- Type: object
- Browser support: Chrome 56+, Chrome Android 56+, Edge 15+, Firefox 44+, Firefox Android 44+, Safari 11+, Safari iOS 11+

## Example

Wrong:

```js
const pc = new RTCPeerConnection();
pc.addEventListener('track', (e) => (video.srcObject = e.streams[0]));
```

Right:

```js
const pc = new RTCPeerConnection({
  iceServers: [
    { urls: 'stun:stun.example.com:3478' },
    { urls: 'turn:turn.example.com:3478', username: 'user', credential: 'secret' }
  ]
});
pc.addEventListener('track', (e) => (video.srcObject = e.streams[0]));
```

Without STUN and TURN servers, peers behind NAT or strict firewalls often fail to connect.

## Common mistakes

- Never handling the 'failed' or 'disconnected' connection states.

## Key points

- The `iceServers` option lists STUN and TURN servers.
- Handlers exist for `icecandidate`, `track` and `connectionstatechange`.
- `close()` is called when the call ends.

## Interview questions

### Do I need a server for WebRTC?

Yes, for signaling. Peers exchange offers, answers and ICE candidates through your own channel, such as a WebSocket, before they connect directly.

### What is the difference between STUN and TURN?

STUN tells a peer its public address so it can try a direct connection. TURN relays the traffic when a direct connection is impossible.

### Why does my WebRTC call work on Wi-Fi but not on mobile data?

Mobile networks often use NAT that blocks direct connections. A TURN server lets the traffic be relayed instead.

## Related cards

- [WebRTC](https://wonderium.dev/web/webrtc.md)
- [SDP](https://wonderium.dev/web/sdp.md)
- [ICE](https://wonderium.dev/web/ice.md)
- [RTCDataChannel](https://wonderium.dev/js/rtc-data-channel.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/rtc-peer-connection
- Last updated: 2026-11-25
