TURN, NAT traversal & troubleshooting
On most home and mobile networks, Trystero's default STUN servers negotiate a direct peer-to-peer path automatically. Around 10–15% of real-world paths—symmetric NATs, corporate firewalls, campus networks, and certain VPNs—block direct UDP hole-punching and require a TURN server as a fallback packet relay.
Signaling, STUN, and TURN
- Signaling (Nostr, MQTT, ws-relay, and others) lets peers discover each other and exchange encrypted SDP offers and ICE candidates.
- STUN (configured by default with Google and Cloudflare STUN endpoints) lets each browser discover its public address for direct NAT hole-punching.
- TURN (configured via
turnConfig) relays encrypted WebRTC packets only for peer pairs whose networks block a direct path. DTLS media and data channels remain end-to-end encrypted between the two browsers when traversing TURN.
During connection setup, signaling relays exchange encrypted offers and
STUN attempts a direct path. If direct ICE checks fail, WebRTC falls back
to turnConfig when provided, or emits
{code: 'peer-connect-failed'} on
room.onError otherwise.
Configuring TURN
- Verify that ICE is failing. If peers connect on local
Wi-Fi or localhost but fail across cellular or corporate networks, check
room.onErrorforerr.code === 'peer-connect-failed'witherr.turnConfigured === false. - Provision a managed or self-hosted TURN server. Managed options include Cloudflare Realtime TURN and Metered Open Relay. Self-hosted servers include coturn, eturnal, Pion TURN, and Violet.
- Pass
turnConfigtojoinRoom().
import {joinRoom} from 'trystero'
const room = joinRoom(
{
appId: 'your-domain.example/chat',
turnConfig: [
{
urls: [
'turn:turn.your-domain.example:3478?transport=udp',
'turns:turn.your-domain.example:5349?transport=tcp'
],
username: 'ephemeral-user',
credential: 'ephemeral-password'
}
]
},
'room-1'
)
room.onError(err => {
if (err.code === 'peer-connect-failed') {
console.warn('ICE failed; TURN configured:', err.turnConfigured)
}
})
Avoid embedding static TURN credentials in client bundles where third
parties can reuse your relay quota. Mint short-lived credentials from a
small serverless endpoint and pass them to joinRoom(); see
the Cloudflare Worker used by this site
for an example.
Custom rtcConfig and trickleIce
rtcConfig accepts a standard RTCConfiguration.
Entries in turnConfig are appended to
rtcConfig.iceServers (or to the default STUN list when
rtcConfig is omitted). To force relay-only connections so
peers do not expose their IP addresses to one another, clear
iceServers and set iceTransportPolicy: 'relay':
const room = joinRoom(
{
appId: 'chat.example.com',
rtcConfig: {iceServers: [], iceTransportPolicy: 'relay'},
turnConfig: [{urls: 'turns:turn.example.com:5349', username, credential}]
},
'room-1'
) trickleIce streams ICE candidates incrementally and defaults
to true on Nostr, MQTT, Supabase, Firebase, and ws-relay, and
false on BitTorrent where offers are announced as single
self-contained payloads.
Measuring latency and inspecting connections
room.ping(id) measures round-trip time in milliseconds over
the data channel to any connected userId or
peerId. Passing a userId pings one active tab
for that user.
room.onUserJoin(({userId}) => {
const timer = setInterval(async () => {
try {
const rttMs = await room.ping(userId)
updateSignalBars(userId, rttMs)
} catch {
clearInterval(timer)
}
}, 5000)
})import {getRelaySockets} from 'trystero'
// Signaling relay sockets (nostr, mqtt, torrent, ws-relay)
console.log(getRelaySockets())
// Connected users and endpoints
console.log(room.getUsers()) // {[userId]: {peerIds, roles}}
console.log(room.getPeers()) // {[peerId]: {userId, connection, direct, hops, roles}}Troubleshooting
| Symptom | Cause and resolution |
|---|---|
onUserJoin does not fire when opening a second tab | Tabs in the same browser profile share one persistent 'local' userId (onPeerJoin fires per tab, while onUserJoin fires once per user). Open an incognito window or set identity: 'none' to test separate users locally. |
Error: already joined room "…" for appId "…" | Calling joinRoom() twice for an active (appId, roomId) throws rather than returning the existing room (often triggered by React Strict Mode double-mounts). Call await room.leave() in cleanup or instantiate the room outside component render lifecycle. |
ReferenceError: window / RTCPeerConnection is not defined in SSR | joinRoom() starts signaling and WebRTC setup immediately. Guard calls behind typeof window !== 'undefined' or initialize inside a client-only module or effect. |
Error when joining a room named my-room~9fX2… | Room names ending in ~<userId> are self-certifying admin rooms created with roles({selfAsAdmin: true}). Guests must pass use: [roles()] so their client verifies room authority. |
| Transfers larger than 256 MiB are rejected | Rooms default to a 256 MiB concurrent receive limit (maxReceiveBytes). Increase maxReceiveBytes in joinRoom() on receivers for larger payloads, noting that incoming transfers buffer in memory. |
| Peers discover each other on relays but never connect | Listen for 'peer-connect-failed' on room.onError. If failures occur across specific networks, configure turnConfig. If every connection fails, verify both peers share the same appId, room ID, signaling strategy, password, and Trystero major/minor protocol version. |
'decrypt-failed' on room.onError | Room password mismatch. Every participant must supply the exact same password string. |