# Bun

> Serve the pipedog WebRTC offer and WebSocket endpoints with Bun.serve.

Source: https://polvallverdu.github.io/pipedog/docs/frameworks/bun/



`Bun.serve` routes both endpoints. `socket` is a fetch handler that upgrades `/ws` with the server
Bun passes to `fetch`, and the `bunWebSocket` handlers deliver each socket's messages and close to
the agent's `WebsocketConnection`.

## Install [#install]

```bash
bun add @pipedog/core @pipedog/asyncio @pipedog/transport-smallwebrtc @pipedog/transport-websocket @pipedog/serializer-protobuf @pipedog/openai @pipedog/audio-silero @pipedog/audio-smart-turn
```

`@pipedog/audio-smart-turn` isn't imported anywhere: the default turn strategies load it. To run
the snippet from a checkout instead, see [Installation](https://polvallverdu.github.io/pipedog/docs/installation/#from-source).

## Files [#files]

The endpoints come from the shared module on the [overview](https://polvallverdu.github.io/pipedog/docs/frameworks/#the-two-endpoints).
`voice.ts` re-exports it:

```ts title="voice.ts"
export { offer, runSocketAgent, socket } from "../shared/voice.ts";

```

```ts title="server.ts"
import { bunWebSocket, type UpgradingServer } from "@pipedog/transport-websocket/fetch";
import { offer, socket } from "./voice.ts";

const config = {
  fetch(request: Request, server: UpgradingServer) {
    const { pathname } = new URL(request.url);
    if (pathname === "/api/offer") return offer(request);
    // `socket` upgrades with the server Bun passes to `fetch`.
    if (pathname === "/ws") return socket(request, server);
    return new Response("not found", { status: 404 });
  },
  // Hands each upgraded socket's messages and close to its connection.
  websocket: bunWebSocket,
};

// `bun server.ts` serves the default export, on port 3000 or $PORT.
export default config;

```

Bun upgrades on its server, not from the `Request` alone, so pass `server` on to `socket` (or to
`upgradeWebSocket(request, { server })` from `@pipedog/transport-websocket/fetch`) and serve with
`websocket: bunWebSocket`. To serve any fetch handler with WebSocket upgrades on Bun, Node or Deno
without this wiring, use `serveFetch()` from `@pipedog/transport-websocket/serve`; see
[WebSocket](https://polvallverdu.github.io/pipedog/docs/transports/websocket.md).

## Run it [#run-it]

```bash
OPENAI_API_KEY=sk-... bun server.ts
```

Bun serves the default export on port 3000, or on `$PORT`. The offer is at `POST /api/offer` and the
WebSocket at `/ws`.

## Deploy [#deploy]

Run it as a long-lived Bun process on a host that allows UDP traffic, for the offer's media. To serve
the same config on Vercel Functions, see [Vercel](https://polvallverdu.github.io/pipedog/docs/frameworks/vercel.md).

## Authentication [#authentication]

Neither route has auth. Check the session in `fetch` before `offer` and `socket` run, as in [Authentication](https://polvallverdu.github.io/pipedog/docs/frameworks/#authentication).
