---
title: "Debugging WebRTC Connections: ICE Candidates, getStats and TURN That Actually Works"
description: "A field guide to WebRTC connection problems: reading ICE candidate types, webrtc-internals, getStats metrics, testing TURN with relay-only mode, coturn pitfalls and ICE restarts."
url: https://sanderyaz.com/en/blog/webrtc-connection-debugging/
author: Sander Yazıcıoğlu
date: 2026-12-05
updated: 2026-12-05
lang: en
tags: ["WebRTC","Realtime","Frontend","DevOps"]
---

# Debugging WebRTC Connections: ICE Candidates, getStats and TURN That Actually Works

"The device screen is black" was one of the most common reports on a real-device testing product that streams phone screens to the browser over WebRTC. The cause was almost never the video pipeline. It was the connection: a corporate firewall that blocked UDP, a TURN server advertising a private address, or a network change that nobody handled. The [WebRTC architecture post](/en/blog/webrtc-device-screen-streaming/) explains the moving parts; this one is about finding out which part failed.

## First question: did ICE ever connect?

Watch the connection state before looking at codecs or bitrates:

```ts
pc.addEventListener('connectionstatechange', () => {
  console.info('pc state', pc.connectionState);
});
pc.addEventListener('icecandidateerror', (e) => {
  console.warn('ICE candidate error', e.url, e.errorCode, e.errorText);
});
```

| State | Meaning |
| --- | --- |
| `connecting` for a long time, then `failed` | No candidate pair worked: a network problem, usually TURN |
| `connected`, then `disconnected` | Path broke (Wi-Fi switch, sleep); may recover by itself |
| `connected` but no video | Media or signaling problem, not connectivity |

The `icecandidateerror` event is underused. An error code of 701 means the STUN or TURN server could not be reached at all, which points straight at DNS, ports or firewalls. Codes in the 400 range come from the server itself, for example 401 for bad TURN credentials.

## Read the candidates

Every ICE candidate has a type, and the types you gathered tell you what the network allows:

- **host**: a local interface address. Chrome hides these behind random `.local` mDNS names for privacy, so do not be surprised by them.
- **srflx** (server reflexive): your public address as seen by a STUN server.
- **relay**: an address on your TURN server. Traffic goes through it.
- **prflx** (peer reflexive): discovered during connectivity checks.

If a client gathers no `srflx` candidates, STUN is blocked. If it gathers no `relay` candidates, your TURN server is unreachable or rejecting the credentials. Logging the candidate types on both sides, sent along with your signaling messages, turns "it does not connect" into a specific answer.

## chrome://webrtc-internals

Open `chrome://webrtc-internals` in a second tab before starting the session (Firefox has `about:webrtc`). It shows every peer connection, every API call in order, every candidate, and live graphs for bitrate, frame rate and round-trip time. Two things I check first:

1. The **selected candidate pair**: which local and remote candidate types won. `relay` on either side means traffic goes through TURN, which costs bandwidth and adds latency.
2. The **event log**: a `setRemoteDescription` error or a missing answer is a signaling bug, not a network one.

You can dump the page to a file and attach it to a bug report, which is far more useful than a screenshot.

## getStats for production telemetry

Internals only helps on your own machine. For users, collect `getStats()` periodically and send a summary to your backend:

```ts
async function sample(pc: RTCPeerConnection) {
  const stats = await pc.getStats();
  let pair: any, video: any;
  stats.forEach((r) => {
    if (r.type === 'candidate-pair' && r.nominated && r.state === 'succeeded') pair = r;
    if (r.type === 'inbound-rtp' && r.kind === 'video') video = r;
  });
  const local = pair && stats.get(pair.localCandidateId);
  return {
    rttMs: pair ? Math.round(pair.currentRoundTripTime * 1000) : null,
    localType: local?.candidateType,     // host, srflx, relay
    fps: video?.framesPerSecond,
    packetsLost: video?.packetsLost,
    jitter: video?.jitter,
    framesDropped: video?.framesDropped,
  };
}
```

Aggregated over sessions, the `localType` field alone is revealing: the share of relayed sessions tells you how much TURN capacity you really need, and a sudden jump usually means a network change at a customer.

## Testing TURN on purpose

The fastest way to prove TURN works is to forbid everything else:

```ts
const pc = new RTCPeerConnection({
  iceServers: [{ urls: 'turns:turn.example.com:443?transport=tcp', username, credential }],
  iceTransportPolicy: 'relay',
});
```

With `iceTransportPolicy: 'relay'`, only relay candidates are used. If the connection fails in this mode, it will also fail for every user on a strict network. The public "Trickle ICE" page in the WebRTC samples does the same test interactively: paste your TURN URL and credentials and check that relay candidates appear.

Offer TURN over TLS on port 443 as well as UDP 3478. Many corporate networks allow only outbound HTTPS, and `turns:` on 443 looks just like it.

## coturn pitfalls

Most TURN problems I have seen were configuration, not software:

```text
listening-port=3478
tls-listening-port=5349
external-ip=203.0.113.10/10.0.0.5
min-port=49152
max-port=65535
use-auth-secret
static-auth-secret=<long random secret>
realm=turn.example.com
```

- **Missing `external-ip` on cloud VMs.** Behind a cloud NAT, coturn advertises its private address in relay candidates and nobody can reach it. Set `external-ip` as public/private.
- **Relay port range closed.** Opening 3478 is not enough; the relay ports (`min-port` to `max-port`) must be open for UDP in the firewall or security group.
- **Static credentials in the frontend.** Anyone can copy them and use your server as a free relay. With `use-auth-secret`, generate short-lived credentials on the backend:

```ts
import crypto from 'node:crypto';

function turnCredentials(userId: string, ttlSec = 3600) {
  const username = `${Math.floor(Date.now() / 1000) + ttlSec}:${userId}`;
  const credential = crypto
    .createHmac('sha1', process.env.TURN_SECRET!)
    .update(username)
    .digest('base64');
  return { username, credential };
}
```

Serve this from an authenticated endpoint, ideally over the same WebSocket used for signaling. The [WebSocket architecture post](/en/blog/websocket-realtime-nodejs/) covers that channel.

## Recovering from network changes

Laptops switch networks and phones move between Wi-Fi and mobile data. When the state goes to `failed`, call `pc.restartIce()`. It triggers a renegotiation with fresh ICE credentials; if you use the "perfect negotiation" pattern, your existing `negotiationneeded` handler sends the new offer. For `disconnected`, wait a few seconds before restarting, because it often recovers on its own.

## Conclusion

Debug WebRTC from the bottom up: connection state and candidate errors, then candidate types, then the selected pair in webrtc-internals, and only then media quality from `getStats`. Prove TURN works with relay-only mode, offer it on 443 over TLS, set `external-ip` and open the relay ports, and never ship static TURN credentials. With that telemetry in place, "the screen is black" becomes a ticket you can actually answer.

---

About the author: [Sander Yazıcıoğlu](https://sanderyaz.com/en/about/). Sander Yazıcıoğlu is a Senior Full-Stack Developer in Istanbul. At LiveTesting he builds the backend, frontend, realtime systems and Appium automation of a real-device testing platform; before that he built enterprise Angular apps at Testinium and Loadium.
