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

# WebSockets

> Use WebSockets in an Edge Script for two-way, low-latency communication between your script and connected clients.

## Enabling WebSockets

To use WebSockets in your scripts, you'll first need to [enable it for your Pull Zone](/docs/cdn/websockets#enabling-websockets) in the Dashboard.

1. Navigate to your Pull Zone -> General -> WebSockets
2. Toggle the "WebSockets" switch
3. Call `request.upgradeWebSocket()` in your script to upgrade incoming connections

## Quickstart

This example creates a WebSocket server that echoes messages back to the client.

```typescript theme={null}
import * as BunnySDK from "@bunny.net/edgescript-sdk";

BunnySDK.net.http.serve(async (request: Request) => {
  const { response, socket } = request.upgradeWebSocket();

  socket.addEventListener("open", () => {
    console.log("Client connected");
  });

  socket.addEventListener("message", (event) => {
    console.log("Received:", event.data);
    socket.send(`Echo: ${event.data}`);
  });

  const closed = new Promise<void>((resolve) => {
    socket.addEventListener("close", (event) => {
      console.log("Client disconnected:", event.code, event.reason);
      resolve();
    });
  });

  // It is important to call waitUntil; otherwise the script may be evicted
  // while the WebSocket connection is still open.
  Bunny.v1.waitUntil(closed);

  return response;
});
```

## upgradeWebSocket

Upgrades an incoming HTTP request to a WebSocket connection.

```typescript theme={null}
const { response, socket } = request.upgradeWebSocket();

// With options
const { response, socket } = request.upgradeWebSocket({
  protocol: "graphql-ws",
  idleTimeout: 60,
});
```

### Parameters

**protocol** `string`

The WebSocket subprotocol to use for the connection.

**idleTimeout** `number` (default: 30)

The number of seconds to wait for a pong response before closing the
connection. If the client does not respond within this timeout, the connection
is deemed unhealthy and closed, emitting the `close` and `error` events. If no
data is transmitted from the client for 2 minutes, the connection will be
closed regardless of this configuration.

### Returns

**response** `Response` *required*

The response to send back to the client to establish the upgrade.

**socket** `WebSocket` *required*

The WebSocket interface to communicate with the client.

## Methods

### close

Closes the WebSocket connection, optionally providing a close code and reason.

```typescript theme={null}
// Close normally
socket.close();

// Close with a code
socket.close(1000);

// Close with a code and reason
socket.close(1000, "Session ended");
```

#### Parameters

**code** `number`

A standardized [WebSocket close
code](https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5). If unset,
defaults to `1000` for normal closure or `1001-1015` for error conditions.

**reason** `string`

A human-readable [close
reason](https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.6) explaining
why the connection was closed.

### send

Transmits data to the connected client.

```typescript theme={null}
// Send a string
socket.send("Hello, client!");

// Send JSON
socket.send(JSON.stringify({ type: "message", content: "Hello" }));

// Send binary data
const buffer = new ArrayBuffer(8);
socket.send(buffer);

// Send a Blob
const blob = new Blob(["Hello"], { type: "text/plain" });
socket.send(blob);
```

#### Parameters

**data** `string | ArrayBufferLike | Blob | ArrayBufferView` *required*

The data to transmit. Can be a string, ArrayBufferLike, Blob, or
ArrayBufferView.

### addEventListener

Registers an event listener for WebSocket events.

```typescript theme={null}
socket.addEventListener("open", () => {
  console.log("Connection established");
});

socket.addEventListener("message", (event) => {
  console.log("Message received:", event.data);
});

socket.addEventListener("close", (event) => {
  console.log("Connection closed:", event.code, event.reason);
});

socket.addEventListener("error", (event) => {
  console.error("WebSocket error occurred");
});
```

#### Parameters

**type** `string` *required*

The event type to listen for. One of: `open`, `message`, `close`, or `error`.

**listener** `function` *required*

The callback function invoked when the event is dispatched.

**options** `boolean | AddEventListenerOptions`

Optional configuration for the event listener.

## Events

### open

Fired when the WebSocket connection is successfully established.

```typescript theme={null}
socket.addEventListener("open", (event) => {
  console.log("Connected to client");
  socket.send("Welcome!");
});
```

**OpenEvent** `Event`

A standard Event object with no additional properties.

### message

Fired when a message is received from the client.

```typescript theme={null}
socket.addEventListener("message", (event) => {
  const data = event.data;

  // Handle string messages
  if (typeof data === "string") {
    const parsed = JSON.parse(data);
    console.log("Received:", parsed);
  }
});
```

**MessageEvent** `object`

**properties**

**data** `any` *required*

The message data sent by the client.

**origin** `string`

The origin of the message.

**lastEventId** `string`

The last event ID string.

**source** `MessageEventSource | null`

The message source.

**ports** `ReadonlyArray\<MessagePort\>`

Any transferred ports.

### close

Fired when the WebSocket connection is closed.

```typescript theme={null}
socket.addEventListener("close", (event) => {
  if (event.wasClean) {
    console.log(`Connection closed cleanly: ${event.code} ${event.reason}`);
  } else {
    console.log("Connection terminated unexpectedly");
  }
});
```

**CloseEvent** `object`

**properties**

**code** `number` *required*

The WebSocket close code provided by the server.

**reason** `string` *required*

The close reason provided by the server.

**wasClean** `boolean` *required*

Whether the connection closed cleanly.

### error

Fired when an error occurs on the WebSocket connection.

```typescript theme={null}
socket.addEventListener("error", (event) => {
  console.error("WebSocket error occurred");
});
```

**ErrorEvent** `Event`

A standard Event object with no additional properties.

## References

* [Server-Sent Events](./server-sent-events), for one-way streaming from the script to the client
* [WebSocket Protocol](https://www.rfc-editor.org/rfc/rfc6455.htm)
* [WebSocket mdn Specification](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/)
* [Runtime - waitUntil](./runtime#waituntil)


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