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

# Small WebRTC Transport

> SmallWebRTCTransport for the JavaScript SDK: peer-to-peer WebRTC to a Pipecat bot with no third-party WebRTC provider.

`SmallWebRTCTransport` enables peer-to-peer WebRTC connections between clients and your Pipecat application. It implements bidirectional audio and video streaming using WebRTC for real-time communication.

This transport is intended for lightweight implementations, particularly for local development and testing. It expects your Pipecat server to include the corresponding [`SmallWebRTCTransport` server-side](https://docs.pipecat.ai/api-reference/server/services/transport/small-webrtc) implementation.

## Usage

### Basic Setup

```javascript theme={null}
import { PipecatClient } from "@pipecat-ai/client-js";
import { SmallWebRTCTransport } from "@pipecat-ai/small-webrtc-transport";

const pcClient = new PipecatClient({
  transport: new SmallWebRTCTransport({
    // Optional configuration for the transport
    iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
  }),
  enableCam: false, // Default camera off
  enableMic: true, // Default microphone on
  callbacks: {
    // Event handlers
  },
});

await pcClient.connect({
  webrtcRequestParams: { endpoint: "/api/offer" }, // Your WebRTC signaling server endpoint
});
```

## API Reference

### Constructor Options

```typescript theme={null}
interface SmallWebRTCTransportConstructorOptions extends SmallWebRTCTransportConnectionOptions {
  iceServers?: RTCIceServer[];
  waitForICEGathering?: boolean;
  audioCodec?: string;
  videoCodec?: string;
  mediaManager?: MediaManager;
  offerUrlTemplate?: string;
}
```

#### Properties

Array of ICE server configurations for connection establishment. Defaults to an empty array: no STUN or TURN server is configured unless you supply one, so a peer behind NAT needs an entry here (the example above uses Google's public STUN server).

```javascript theme={null}
// Set custom ICE servers
transport.iceServers = [
  { urls: "stun:stun.l.google.com:19302" },
  { urls: "stun:stun1.l.google.com:19302" },
];
```

If `true`, the transport waits up to 2 seconds for ICE gathering to complete
before sending the offer. If gathering completes while the ICE connection is
still `checking`, the transport reconnects to use the new candidates.

The WebRTC signaling server's offer endpoint, as an
[`APIRequest`](https://docs.pipecat.ai/api-reference/client/js/client-methods#startbot). This
endpoint may also be provided as part of `connect()`, which replaces it.

*Deprecated since 1.4.0.* Use `webrtcRequestParams` instead.

Template for the offer URL when `startBotAndConnect()` returns a session ID,
with `:sessionId` as the placeholder. When unset, the transport replaces
`/start` in the start endpoint with `/sessions/{sessionId}/api/offer`.

Preferred audio codec to use. If not specified, your browser default will be
used.

Preferred video codec to use. If not specified, your browser default will be
used.

The media manager to use for handling local audio and video streams. This
should not be overridden unless you have a specific reason to use a different
media manager. The default is `DailyMediaManager`, which is suitable for most
use cases. Note that the `DailyMediaManager` does not use any of Daily's
services, it simply takes advantage of vast media support provided by the
Daily library. The package exports `DailyMediaManager` and `WavMediaManager`.

### TransportConnectionParams

```typescript theme={null}
export type SmallWebRTCTransportConnectionOptions = {
  /** @deprecated Use webrtcRequestParams instead */
  connectionUrl?: string;
  /** @deprecated Use webrtcRequestParams instead */
  webrtcUrl?: string;
  webrtcRequestParams?: APIRequest;
  iceConfig?: IceConfig;
};
```

On `connect()`, the `SmallWebRTCTransport` optionally takes a set of connection parameters. This can be provided directly to the `PipecatClient`'s `connect()` method or via a starting endpoint passed to the `PipecatClient`'s `startBotAndConnect()` method. If using an endpoint, your endpoint should return a JSON object matching the `SmallWebRTCTransportConnectionOptions` type. Snake\_case keys are converted to camelCase, and unrecognized keys are ignored with a warning. If the response has a `sessionId` (or `session_id`) and no offer endpoint, the transport builds the offer URL from the start endpoint, or from `offerUrlTemplate`.

Use `webrtcRequestParams` to give the offer endpoint as an [`APIRequest`](https://docs.pipecat.ai/api-reference/client/js/client-methods#startbot), which allows headers and request data alongside the URL. `iceConfig` supplies ICE servers for this connection, overriding the constructor's `iceServers`. It is read only from `connect()`, so an `iceConfig` passed to the constructor is ignored.

```typescript client theme={null}
pcClient.startBotAndConnect({
  endpoint: '/api/start', // Your server endpoint to start the bot and return the connection params
});
// OR...
pcClient.connect({
  webrtcRequestParams: { endpoint: '/api/offer' }, // Your WebRTC offer/answer endpoint
});
```

```python server theme={null}
# See
# https://github.com/pipecat-ai/pipecat-examples/blob/main/p2p-webrtc/voice-agent/server.py
# for a complete example of how to implement the server-side endpoint.
from pipecat.transports.smallwebrtc.connection import SmallWebRTCConnection

@app.post("/api/offer")
async def offer(request: dict, background_tasks: BackgroundTasks):
    pipecat_connection = SmallWebRTCConnection(ice_servers)
    await pipecat_connection.initialize(sdp=request["sdp"], type=request["type"])

    @pipecat_connection.event_handler("closed")
    async def handle_disconnected(webrtc_connection: SmallWebRTCConnection):
        logger.info(f"Discarding peer connection for pc_id: {webrtc_connection.pc_id}")
        pcs_map.pop(webrtc_connection.pc_id, None)

    background_tasks.add_task(run_bot, pipecat_connection)

    answer = pipecat_connection.get_answer()

    return answer
```

### Methods

For most operations, you will not interact with the transport directly. Most methods have an equivalent in the `PipecatClient` and should be called from the `PipecatClient`. However, there are a few transport-specific methods that you may need to call directly. When doing so, be sure to access your transport via the `transport` property of the `PipecatClient` instance.

**setAudioCodec** `method`

Sets the preferred audio codec.

```javascript theme={null}
transport.setAudioCodec("opus");
```

**setVideoCodec** `method`

Sets the preferred video codec.

```javascript theme={null}
transport.setVideoCodec("VP8");
```

## Media Support

`SmallWebRTCTransport` carries bot audio and bot video. What the user can send follows the configured media manager, so `screenShare` is `false` where the media manager or browser can't share the screen. See [`mediaSupport`](https://docs.pipecat.ai/api-reference/client/js/client-methods#mediasupport).

## Events

The transport implements the various [`PipecatClient` event handlers](https://docs.pipecat.ai/api-reference/client/js/callbacks).

## Connection Process

The connection process follows these steps:

1. The transport negotiates a WebRTC connection with the corresponding pipecat transport, complete with transceivers for the media and a data channel for messaging.
2. The transport sends a message to the pipecat transport to let it know it's ready.
3. The Pipecat transport sends a message letting the client know it is ready.

## Reconnection Handling

The transport includes automatic reconnection logic:

* Up to 3 reconnection attempts for transient connection failures (network errors, 5xx responses); authentication and validation errors (4xx responses) fail immediately without retry
* Detection of ICE connection state changes
* Graceful recovery from temporary disconnections
* Graceful disconnect when reconnection attempts fail

## More Information

> [card] [Video Transform Demo](https://github.com/pipecat-ai/pipecat-examples/tree/main/p2p-webrtc/video-transform)
>
> Real-time video transformation example

> [card] [Package](https://www.npmjs.com/package/@pipecat-ai/small-webrtc-transport)
>
> `@pipecat-ai/small-webrtc-transport`


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.