> ## Documentation Index
> Fetch the complete documentation index at: https://docs.poly.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# WebRTC Bridge API

> Talk to a PolyAI voice agent from a browser or app over WebRTC, with media carried by Cloudflare.

The WebRTC Bridge connects a WebRTC client to a PolyAI voice agent. Your client sends and receives audio over [WebRTC](https://webrtc.org/getting-started/overview). Cloudflare carries the media. The bridge does the signaling over HTTPS, and sends call events on one WebSocket.

> [!NOTE]
>
> The WebRTC Bridge replaces the WebRTC Gateway. The gateway endpoint (`wss://webrtc-gateway.<region>.platform.polyai.app/api/v1/webrtc/signal`) is retired and does not accept calls. The WebRTC token that you used with the gateway also works with the bridge.

> [!TIP]
>
> To add a voice call to a web page without code, use the [Web Calling widget](https://docs.poly.ai/widgets/web-calling.md) or the [Android](https://docs.poly.ai/messaging-channel/android-sdk-voice.md) and [iOS](https://docs.poly.ai/messaging-channel/ios-sdk-voice.md) voice SDKs. Use this API only when you build your own WebRTC client.

## Before you start

* A WebRTC token for your project. See [Authentication](#authentication).
* A browser or WebRTC library that supports Unified Plan SDP and renegotiation. Current versions of Chrome, Edge, Firefox and Safari do.
* Permission to use the microphone. Browsers allow `getUserMedia` only on HTTPS pages and on `localhost`.

## How a call works

```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
sequenceDiagram
    participant Browser
    participant Backend as Your backend
    participant Bridge as WebRTC Bridge
    participant CF as Cloudflare

    Backend->>Bridge: POST /api/v1/call (WebRTC token)
    Bridge-->>Backend: callId, call token, ICE servers
    Backend-->>Browser: callId, call token, ICE servers
    Browser->>Backend: SDP offer (microphone)
    Backend->>Bridge: POST /api/v1/call/{callId}/sdp
    Bridge-->>Browser: SDP answer (through your backend)
    Browser->>Bridge: Open the events WebSocket and send the call token
    Browser<<->>CF: WebRTC connected
    Browser->>Backend: Pull the agent audio
    Backend->>Bridge: POST /api/v1/call/{callId}/sdp/pull
    Bridge-->>Browser: SDP offer with the agent track
    Browser->>Backend: SDP answer
    Backend->>Bridge: POST /api/v1/call/{callId}/sdp/renegotiate
    Note over Browser,CF: Two-way audio (Opus)
```

1. **Provision.** Your backend creates the call with your WebRTC token. The bridge returns a call ID, a call token and the ICE servers.
2. **Connect the microphone.** The client sends an SDP offer for its microphone track. The bridge returns the answer.
3. **Open the events socket.** The client opens a WebSocket for call events. It keeps the socket open for the whole call.
4. **Pull the agent audio.** When the peer connection is connected, the client asks for the agent track. The bridge returns a new offer, and the client answers it.
5. **Hang up.** Close the events socket, or send `DELETE /api/v1/call/{callId}`.

The bridge does not use trickle ICE. Gather candidates before you send an offer. Stop after about 2 seconds, and send the candidates that you have.

### Time limits

| Limit | Value | What happens |
| - | - | - |
| From provision to the microphone offer | 30 seconds | The bridge ends the call. |
| From the microphone offer to the first caller audio | 30 seconds | The bridge ends the call. |
| Events socket authentication | 5 seconds after it opens | The bridge closes the socket with `1008`. The call continues. Open a new socket, or send `DELETE`. |
| Call token lifetime | 1 hour | The bridge does not end the call. Signaling requests and `DELETE` get `401`. Media that goes through TURN, or that must reconnect, fails. To end the call, close the events socket. |

If setup fails at any step, send `DELETE /api/v1/call/{callId}`. If you do not, the call holds resources until a time limit ends it.

## Call the bridge from your backend

The bridge only accepts cross-origin browser requests from PolyAI origins. A page on your own domain cannot read the bridge's HTTPS responses.

Send every HTTPS request from your backend:

* `POST /api/v1/call` uses your WebRTC token. **Do not send the WebRTC token to the browser.**
* The signaling routes (`/sdp`, `/sdp/pull`, `/sdp/renegotiate`) and `DELETE` use the call token. Your backend relays them for the browser.
* Authenticate your own users before you provision a call. If you do not, anyone can start calls on your account.

The browser connects directly for two things only:

* The WebRTC peer connection, to Cloudflare.
* The events WebSocket, to the bridge. WebSocket connections are not subject to CORS. If your page has a Content Security Policy, add your bridge host from [Endpoints](#endpoints) to `connect-src` with the `wss://` scheme, for example `wss://webrtc-bridge.us-1.platform.polyai.app`.

A native or server client, which is not a browser, can call every route directly.

> [!WARNING]
>
> The bridge limits HTTPS requests from each source IP address to 10 a second, with bursts of up to 20. When you relay through your backend, all your users share your backend's IP address. One call uses 4 to 6 requests, and 2 more for each `repull`. If you expect more than 2 new calls a second, contact PolyAI before you go live.

## Authentication

| Token | Where it comes from | Used on |
| - | - | - |
| **WebRTC token** | Dialog Studio › Connector Settings. It is the same token that the WebRTC Gateway accepted as `authToken`. It is not the connector API key. | `POST /api/v1/call`, as `Authorization: Bearer <WebRTC token>` |
| **Call token** | `creds.token` in the provision response. It is valid for one call only. | The signaling routes, `DELETE`, and the events WebSocket |

Keep the WebRTC token on your server. The call token is safe to give to the browser.

## Endpoints

Use the host in the region where your project is deployed.

| Region | Base URL |
| - | - |
| US | `https://webrtc-bridge.us-1.platform.polyai.app` |
| UK | `https://webrtc-bridge.uk-1.platform.polyai.app` |
| EU | `https://webrtc-bridge.euw-1.platform.polyai.app` |
| Self-serve Dialog Studio (`studio.poly.ai`) | `https://webrtc-bridge.plg-us-1-prod.polyai.app` |

See the [API reference](https://docs.poly.ai/api-reference/webrtc-bridge/reference.md) for each route.

## Example

This example has two parts: a Node.js backend that relays requests, and the browser code. It uses `us-1`. Change the host for your region. It is a starting point, not production code.

### Backend (Node.js 22 or later, Express 5)

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import express from 'express';

const BRIDGE = 'https://webrtc-bridge.us-1.platform.polyai.app';
const WEBRTC_TOKEN = process.env.POLYAI_WEBRTC_TOKEN;
// The only bridge paths that the browser can reach through this relay.
const SIGNALING = /^\/api\/v1\/call\/[\w-]+\/(sdp|sdp\/pull|sdp\/renegotiate)$/;

const app = express();
app.use(express.json());

// Forward one request to the bridge. Pass the status, body and content type through.
async function relay(req, res, path, init) {
  const abort = new AbortController();
  res.on('close', () => abort.abort());
  try {
    const r = await fetch(`${BRIDGE}${path}`, {
      ...init,
      signal: AbortSignal.any([abort.signal, AbortSignal.timeout(30_000)]),
    });
    res.status(r.status);
    const type = r.headers.get('Content-Type');
    if (type) res.type(type);
    res.send(await r.text());
  } catch {
    if (!res.headersSent) res.sendStatus(502);
  }
}

// TODO: authenticate your user before this route. It starts a call on your account.
app.post('/voice/call', (req, res) =>
  relay(req, res, '/api/v1/call', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${WEBRTC_TOKEN}`,
      'Content-Type': 'application/json',
    },
    // This relay does not forward caller or variantId. Set them here if you need them.
    body: JSON.stringify({ mode: 'voice-agent' }),
  }),
);

// Relay a signaling path from the provision response. Forward only the call token.
app.post('/voice/bridge/*path', (req, res) => {
  const path = `/${req.params.path.join('/')}`;
  if (!SIGNALING.test(path)) return res.sendStatus(404);
  relay(req, res, path, {
    method: 'POST',
    headers: {
      'X-Call-Token': req.get('X-Call-Token') ?? '',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(req.body ?? {}),
  });
});

app.delete('/voice/call/:callId', (req, res) => {
  if (!/^[\w-]+$/.test(req.params.callId)) return res.sendStatus(404);
  relay(req, res, `/api/v1/call/${req.params.callId}`, {
    method: 'DELETE',
    headers: { 'X-Call-Token': req.get('X-Call-Token') ?? '' },
  });
});

app.listen(3000);
```

### Browser

Load this as a module: `<script type="module" src="call.js"></script>`. Start it from a click, so that the browser lets the page play audio. To cancel during setup, pass an `AbortSignal` and abort it.

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const BRIDGE_WS = 'wss://webrtc-bridge.us-1.platform.polyai.app';

export async function startCall(audio, { signal } = {}) {
  signal?.throwIfAborted();
  const stop = new AbortController(); // Aborts when the call ends.
  const ended = new Promise((resolve) => stop.signal.addEventListener('abort', resolve));
  let mic, call, pc, events;
  let deleted = false;

  // Safe to call more than once, and at any step.
  const hangUp = () => {
    stop.abort(new Error('call ended'));
    signal?.removeEventListener('abort', hangUp);
    events?.close();
    pc?.close();
    mic?.getTracks().forEach((t) => t.stop());
    if (call && !deleted) {
      deleted = true;
      fetch(`/voice/call/${encodeURIComponent(call.callId)}`, {
        method: 'DELETE',
        headers: { 'X-Call-Token': call.creds.token },
      }).catch(() => {});
    }
  };
  signal?.addEventListener('abort', hangUp);

  // Send a request to a path from the provision response, through your relay.
  const post = async (path, body) => {
    const res = await fetch(`/voice/bridge${path}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'X-Call-Token': call.creds.token },
      body: JSON.stringify(body),
      signal: stop.signal,
    });
    if (!res.ok) throw new Error(`${path} failed: ${res.status}`);
    return res.status === 204 ? null : res.json();
  };

  // Wait until check() returns true. Reject if check() throws, the call ends, or ms passes.
  // With timeoutOk, resolve when ms passes.
  const waitFor = (check, ms, timeoutOk = false) =>
    new Promise((resolve, reject) => {
      const finish = (err) => {
        clearTimeout(timer);
        pc.removeEventListener('icegatheringstatechange', tick);
        pc.removeEventListener('connectionstatechange', tick);
        stop.signal.removeEventListener('abort', onAbort);
        if (err) reject(err);
        else resolve();
      };
      const tick = () => {
        try {
          if (check()) finish();
        } catch (err) {
          finish(err);
        }
      };
      const onAbort = () => finish(stop.signal.reason);
      const timer = setTimeout(() => finish(timeoutOk ? null : new Error('timed out')), ms);
      pc.addEventListener('icegatheringstatechange', tick);
      pc.addEventListener('connectionstatechange', tick);
      stop.signal.addEventListener('abort', onAbort);
      if (stop.signal.aborted) onAbort();
      else tick();
    });

  try {
    // 1. Get the microphone first. If the user denies it, no call is created.
    mic = await navigator.mediaDevices.getUserMedia({ audio: true });
    stop.signal.throwIfAborted();

    // 2. Create the call.
    const r = await fetch('/voice/call', { method: 'POST' });
    if (!r.ok) throw new Error(`provision failed: ${r.status}`);
    call = await r.json();
    stop.signal.throwIfAborted();
    const { creds } = call;

    pc = new RTCPeerConnection({
      iceServers: creds.iceServers?.length
        ? creds.iceServers
        : [{ urls: 'stun:stun.cloudflare.com:3478' }],
      iceTransportPolicy: creds.iceTransportPolicy === 'relay' ? 'relay' : 'all',
    });
    const micTx = pc.addTransceiver(mic.getAudioTracks()[0], { direction: 'sendrecv' });
    pc.onconnectionstatechange = () => {
      if (pc.connectionState === 'failed') hangUp();
    };

    // Agent audio arrives on the tracks that the pull adds. A new track keeps the mute state.
    const agentStream = new MediaStream();
    let agentMuted = false;
    audio.srcObject = agentStream;
    audio.autoplay = true;
    pc.ontrack = (e) => {
      if (e.transceiver === micTx) return;
      agentStream.getTracks().forEach((t) => agentStream.removeTrack(t));
      e.track.enabled = !agentMuted;
      agentStream.addTrack(e.track);
    };
    const setAgentAudio = (on) => {
      agentMuted = !on;
      agentStream.getTracks().forEach((t) => { t.enabled = on; });
    };

    // 3. Send the microphone offer. Gather ICE candidates for up to 2 seconds.
    await pc.setLocalDescription(await pc.createOffer());
    await waitFor(() => pc.iceGatheringState === 'complete', 2000, true);
    const answer = await post(creds.connectUrl, { sdp: pc.localDescription.sdp, mid: micTx.mid });
    await pc.setRemoteDescription({ type: 'answer', sdp: answer.sdp });
    stop.signal.throwIfAborted();

    // 4. Open the events socket. Keep it open: closing it ends the call.
    events = new WebSocket(`${BRIDGE_WS}${creds.extra.eventsUrl}`);
    events.onopen = () => events.send(JSON.stringify({ type: 'auth', token: creds.token }));
    events.onclose = hangUp;

    // 5. Pull the agent track. Run one pull at a time. A failed pull does not stop later pulls.
    let pulls = Promise.resolve();
    let connected = false;
    const pullAgent = () =>
      (pulls = pulls.catch(() => {}).then(async () => {
        const offer = await post(creds.extra.pullUrl, {});
        if (!offer?.sdp) return;
        await pc.setRemoteDescription({ type: 'offer', sdp: offer.sdp });
        await pc.setLocalDescription(await pc.createAnswer());
        await post(creds.extra.renegotiateUrl, { sdp: pc.localDescription.sdp });
      }));
    events.onmessage = ({ data }) => {
      let event;
      try {
        ({ event } = JSON.parse(data));
      } catch {
        return;
      }
      if (typeof event !== 'string') return;
      // A failed repull does not end the call. The bridge sends another repull.
      if (event === 'repull' && connected) pullAgent().catch((err) => console.warn(err));
      else if (event.startsWith('barge-in')) setAgentAudio(false);
      else if (event === 'unmute') setAgentAudio(true);
    };

    await waitFor(() => {
      if (['failed', 'disconnected', 'closed'].includes(pc.connectionState)) {
        throw new Error(`peer connection ${pc.connectionState}`);
      }
      return pc.connectionState === 'connected';
    }, 15_000);
    connected = true;
    await pullAgent();
  } catch (err) {
    hangUp();
    throw err;
  }

  return {
    hangUp,
    // Resolves when the call ends, for any reason.
    ended,
    // Send one keypad digit to the agent. Call this once for each keypress.
    sendDigit: (digit) => {
      if (/^[0-9*#]$/.test(digit) && events.readyState === WebSocket.OPEN) {
        events.send(JSON.stringify({ type: 'dtmf', digits: digit }));
      }
    },
  };
}
```

A production client also needs a timeout on each request, and must handle a lost connection. The [API reference](https://docs.poly.ai/api-reference/webrtc-bridge/reference.md#troubleshooting) lists the failures to handle.

## Useful links

* [WebRTC overview](https://webrtc.org/getting-started/overview)
* [MDN WebRTC API](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API)
* [RFC 8866 (SDP)](https://datatracker.ietf.org/doc/html/rfc8866)
