With Cloudflare Realtime TURN, how does a backend turn a TURN key into short-lived credentials for browsers, and how long may they last?
answer
- the key itself never reaches turn.cloudflare.com
- an endpoint that returns iceServers
- a ttl sized to the longest call
- a two-day ceiling
basics
~20 sA TURN key is a long-term server-side secret that cannot authenticate to turn.cloudflare.com. The backend calls the key's generate-ice-servers endpoint with a ttl, up to 48 hours, and hands the returned iceServers to the browser.
solid answer
~40 sCreate a **TURN key** in the dashboard or through the API and keep its ID and API token on the backend; the key cannot be used as a credential with `turn.cloudflare.com` itself. When a signed-in user starts a call, the backend calls `POST https://rtc.live.cloudflare.com/v1/turn/keys/{keyId}/credentials/generate-ice-servers` with `Authorization: Bearer <key API token>` and a body such as `{"ttl": 14400}`. The `201` response holds an `iceServers` array (Cloudflare STUN plus TURN URLs over UDP, TCP and TLS with a generated username and credential) that the browser passes to `RTCPeerConnection`. Set `ttl` longer than the longest expected call, at most 48 hours; refresh mid-call with `setConfiguration()`, and revoke a credential early through the key's `credentials/{username}/revoke` endpoint.
code
javascript · 36 linesconst TURN_API = "https://rtc.live.cloudflare.com/v1/turn/keys";
// The app's own login check; here a session cookie looked up in KV.
async function authenticate(request, env) {
const id = request.headers.get("Cookie")?.match(/session=([^;]+)/)?.[1];
return id ? env.SESSIONS.get(id) : null;
}
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (url.pathname !== "/api/turn-credentials" || request.method !== "POST") {
return new Response("Not found", { status: 404 });
}
const user = await authenticate(request, env);
if (!user) {
return new Response("Unauthorized", { status: 401 });
}
const upstream = await fetch(
`${TURN_API}/${env.TURN_KEY_ID}/credentials/generate-ice-servers`,
{
method: "POST",
headers: {
Authorization: `Bearer ${env.TURN_KEY_API_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ ttl: 4 * 60 * 60 }),
},
);
if (upstream.status !== 201) {
return new Response("TURN credentials unavailable", { status: 502 });
}
const { iceServers } = await upstream.json();
return Response.json({ iceServers }, { headers: { "Cache-Control": "no-store" } });
},
};go deeper
Recall that a TURN key stays on the server and that browsers get generated, expiring credentials as an iceServers array.
Explain the generate-ice-servers call, the ttl and its 48-hour ceiling, setConfiguration refresh and per-username revocation.
Show the production habits: authenticated issuance, no-store responses, keys per environment, customIdentifier tagging and a refresh path for long calls.
Discuss the abuse and billing exposure of an open credential endpoint and how analytics per customIdentifier feeds cost allocation.
## Two kinds of secret Cloudflare Realtime TURN separates a long-term secret from the credentials browsers actually use: - A **TURN key** is created in the dashboard or through the API, and has an ID and an API token. It lets you generate an unlimited number of credentials and revoke them. It **cannot** be used as a username and password against `turn.cloudflare.com`, and it must stay on the server. - A **TURN credential** is a generated username and credential with an expiry. This is what goes into the browser's `iceServers`. The reason to hand out short-lived credentials at all is covered with WebRTC NAT traversal. The Cloudflare part is the API that produces them and the limits that apply. ## Generating credentials 1. Authenticate the user with your own session check before issuing anything; an open credentials endpoint would turn your TURN bill into anyone's relay. 2. Call `POST https://rtc.live.cloudflare.com/v1/turn/keys/{keyId}/credentials/generate-ice-servers` with `Authorization: Bearer <TURN key API token>`, `Content-Type: application/json` and a body such as `{"ttl": 14400}`. 3. A **201 Created** response returns an `iceServers` array ready for `new RTCPeerConnection({ iceServers })`: - a STUN entry, `stun:stun.cloudflare.com:3478`; - TURN entries on `turn.cloudflare.com` over UDP (3478, 443), TCP (3478, 80) and TLS (`turns:` on 5349 and 443), sharing one generated `username` and `credential`. 4. Return it to the browser with `Cache-Control: no-store`, so no shared cache keeps one user's credential for another. The worker in the code example shows those steps. ## How long credentials last | Setting or behaviour | What the docs say | | --- | --- | | `ttl` | Seconds until the credential expires; set it longer than the longest call you expect | | Maximum expiry | Up to **48 hours** in the future | | Longer calls | Generate a new credential and apply it with `RTCPeerConnection.setConfiguration()` before expiry | | Allocation lifetime | No maximum; the client keeps it alive with Refresh requests authenticated by a valid credential | | Credential expires mid-call | Cloudflare stops billing and analytics at once, and the connection drops after a short delay | | Early revocation | `POST .../turn/keys/{keyId}/credentials/{username}/revoke` returns **204 No Content** | So a `ttl` of a few minutes is a bug for a 40-minute consultation: the relay works at first, then relayed participants fall off the call once their credential expires. ## Operating TURN keys at scale - **One key per environment.** An account can hold up to 1,000 TURN keys, and each key can issue unlimited credentials, so staging and production get separate keys. - **Tag credentials.** The `credentials/generate` call accepts a `customIdentifier` (for example an internal clinic ID), which appears as a dimension in TURN analytics. That lets you spot one tenant's unusual usage or bill it. - **Issuance rate.** No limit is defined; the docs suggest starting around 500 credentials per second, scaling up linearly, and actually using more than half of what you issue. - **Billing.** TURN bills egress from Cloudflare to the TURN client at $0.05 per GB, with a 1,000 GB monthly allowance shared with the SFU, and traffic between TURN and the Realtime SFU is not charged twice. `stun.cloudflare.com` is free and unlimited. ## Checking the setup 1. Call the credentials endpoint without a session and confirm it refuses before it calls the TURN API. 2. Call it signed in and check that the response holds STUN and TURN entries and is marked `no-store`. 3. In a test client, restrict ICE to relay candidates and confirm a call still connects through `turn.cloudflare.com`. 4. Look for the usage in TURN analytics, where it shows up within about 30 seconds, grouped by `customIdentifier` if you set one. ## Where people go wrong - Shipping the TURN key's API token in a mobile app or a page so clients can mint their own credentials. - Setting a short `ttl` "for security" without a refresh path, then chasing call drops that happen at the same minute into every relayed call. - Assuming the SFU hands out TURN servers. A browser on the Realtime SFU still needs these `iceServers` from your backend; RealtimeKit is the product that configures TURN for you. - Treating one leaked credential as a reason to replace the whole TURN key, when the per-username revoke endpoint exists for exactly that case.
- A consultation may run past the credential's ttl; how do you keep relayed participants connected?Before the credential expires, fetch a fresh `iceServers` set from your backend and apply it with `RTCPeerConnection.setConfiguration()`, so the client keeps refreshing its allocation with a valid credential. A credential can be valid for at most 48 hours, so very long sessions need this refresh anyway.
- One clinic's credentials appear in a public script; what do you do without disrupting other clinics?Revoke the affected usernames with `POST .../turn/keys/{keyId}/credentials/{username}/revoke`, which returns 204, and fix how that clinic obtains credentials. Tagging credentials with a `customIdentifier` lets you find that clinic's traffic in TURN analytics. Revoking per username leaves every other clinic's credentials untouched.
- The TURN key's API token can be put directly into the browser's iceServers.
- A TURN credential can be issued with any expiry, including several weeks.
- A credential that expires mid-call has no effect until the call ends.
- The Realtime SFU session API returns TURN servers for the browser.
- Revoking one leaked credential requires deleting the whole TURN key.