Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 36 ยท Servers: STUN, TURN and SFU

TURN Servers: Relaying Media When Direct Paths Fail

Learn when WebRTC needs a TURN relay, how ephemeral TURN credentials are generated with HMAC, how to force relay mode, and what a basic coturn setup looks like.

STUN lets two peers learn their public addresses, but some networks still refuse a direct path: symmetric NATs, strict corporate firewalls, or networks that block UDP altogether. In those cases the only way to connect is to send everything through a TURN server (Traversal Using Relays around NAT), a machine with a public address that forwards packets between the two peers.

A relayed call is still encrypted end to end between the browsers (DTLS-SRTP, see Security: DTLS and SRTP); the TURN server only sees encrypted packets. But it does carry all the bandwidth, so TURN is the expensive part of a WebRTC deployment. Expect roughly 10 to 20 percent of real-world sessions to need it, which is enough that no production service can skip it.

Honest note: the sandbox in this site's preview cannot connect to a TURN server, and running coturn needs a real machine. The server configuration below is read-only; the runnable examples work on the client side (configuration, policy and credential generation).

How a relay allocation works

  1. The browser authenticates to the TURN server and asks for an allocation, which reserves a relayed address and port on the server.
  2. The server answers with that relayed transport address. The browser sends it to the peer as a relay candidate through signalling.
  3. The peer sends packets to the relayed address; the server forwards them to your browser (and the reverse).
flowchart LR
  A["Browser A"] -- "TURN allocation (UDP, TCP or TLS)" --> T["TURN server relay address 198.51.100.9:49200"]
  B["Browser B"] -- "sends to relay address" --> T
  T -- "forwards" --> A
  A -- "forwards" --> T

Neither browser needs a direct route to the other; both only need a route to the TURN server.

TURN is reachable over several transports, in order of friendliness to firewalls: UDP on 3478, TCP on 3478, and TLS on port 443, which looks like ordinary HTTPS and passes through most corporate proxies. A good configuration lists several:

JavaScript
const pc = new RTCPeerConnection({
  iceServers: [
    { urls: 'stun:turn.example.org:3478' },
    {
      urls: [
        'turn:turn.example.org:3478?transport=udp',
        'turn:turn.example.org:3478?transport=tcp',
        'turns:turn.example.org:443?transport=tcp',
      ],
      username: '1900000000:maria',
      credential: 'derived-secret-goes-here',
    },
  ],
});

Credentials: never ship a permanent password

TURN servers need authentication, otherwise anybody could use your bandwidth. Putting one fixed username and password into your JavaScript is a bad idea: everyone can read it and reuse it.

The standard solution is ephemeral (time-limited) credentials from the "TURN REST API" convention, supported by coturn with use-auth-secret:

  • Your backend and the TURN server share one secret.
  • The username is expiryTimestamp:userId.
  • The password is base64(HMAC-SHA1(secret, username)).
  • After the timestamp, the credentials stop working.

Your web backend computes this per user and returns it from an authenticated endpoint. The secret never reaches the browser.

JS Compute a TURN credential with HMAC-SHA1

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The "expected" value was computed independently with Node's crypto module, so a match shows the page and the server agree on the formula. Keep ttlSeconds short (hours, not months); the credential only needs to survive the call setup and any ICE restarts.

Forcing relay mode

By default ICE tries every candidate and chooses the best working pair. Setting iceTransportPolicy: 'relay' tells the browser to use only relay candidates. This has two uses:

  • Testing: prove that your TURN server works by making sure no direct path is used.
  • Privacy: hide the user's IP address from the peer (the peer sees only the TURN address). See Privacy and Permissions.
JS Relay-only policy gathers no host candidates

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In production a relay-only test fails the same way if TURN is misconfigured, which is exactly why the test is useful: zero candidates, or relay candidates only when it works.

A minimal coturn configuration (read-only)

coturn is the most widely used open-source TURN server. This is a trimmed turnserver.conf, shown for understanding, not runnable here:

INI
# /etc/turnserver.conf  (read-only example)
listening-port=3478
tls-listening-port=5349
listening-ip=0.0.0.0
external-ip=198.51.100.9
realm=turn.example.org

# ephemeral credentials shared with your backend
use-auth-secret
static-auth-secret=CHANGE_ME_LONG_RANDOM

# range of relay ports (open these in the firewall)
min-port=49152
max-port=65535

fingerprint
no-multicast-peers
no-cli
# never relay to private networks (SSRF protection)
denied-peer-ip=10.0.0.0-10.255.255.255
denied-peer-ip=172.16.0.0-172.31.255.255
denied-peer-ip=192.168.0.0-192.168.255.255
cert=/etc/letsencrypt/live/turn.example.org/fullchain.pem
pkey=/etc/letsencrypt/live/turn.example.org/privkey.pem

Notes that save hours:

  • Open UDP and TCP on 3478, TLS on 5349 (or 443 with a proper proxy setup), and the relay port range.
  • external-ip is required when the server sits behind NAT, as on most cloud VMs.
  • denied-peer-ip rules stop attackers from using your TURN server to reach internal machines.
  • Monitor bandwidth. Relayed video is expensive; put a cap per user.

Common mistakes

  • Hard-coded static credentials in client code.
  • Only listing UDP URLs. Users behind UDP-blocking firewalls never connect; add TCP and turns: on 443.
  • Forgetting external-ip on a cloud server, so the relay candidate advertises a private address.
  • Skipping the relay-only test before launch.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does a WebRTC session fall back to TURN?

    ICE prefers direct paths; TURN relay candidates are used when connectivity checks on direct candidates fail.
  2. 2. How is an ephemeral TURN password derived?

    The username embeds an expiry timestamp, and the password is an HMAC of that username under a secret known to the backend and the TURN server.
  3. 3. What does iceTransportPolicy: 'relay' do?

    It restricts ICE to relay candidates, useful to test TURN or to hide the user's IP.
  4. 4. Why list a turns: URL on port 443?

    Traffic on 443 looks like HTTPS, so networks that block UDP and unusual ports still allow it.
  5. 5. Can the TURN server read the media it relays?

    DTLS-SRTP keys are negotiated between the browsers; the relay forwards encrypted packets.

Summary

  • TURN relays all traffic when direct paths fail; it costs bandwidth, so plan for it.
  • Offer UDP, TCP and turns: on 443 to cover strict networks.
  • Use short-lived HMAC credentials generated by your backend, never fixed passwords.
  • iceTransportPolicy: 'relay' tests TURN and hides IPs.
  • Run coturn with external-ip, an open relay port range and private-network deny rules.

Next: Mesh, MCU and SFU Topologies