Skip to main content

Enabling WebSockets

To use WebSockets in your scripts, you’ll first need to enable it for your Pull Zone 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.
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}`);
  });

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

  return response;
});

upgradeWebSocket

Upgrades an incoming HTTP request to a WebSocket connection.
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.
// 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. If unset, defaults to 1000 for normal closure or 1001-1015 for error conditions.
reason
string
A human-readable close reason explaining why the connection was closed.

send

Transmits data to the connected client.
// 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.
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.
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.
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

close

Fired when the WebSocket connection is closed.
socket.addEventListener("close", (event) => {
  if (event.wasClean) {
    console.log(`Connection closed cleanly: ${event.code} ${event.reason}`);
  } else {
    console.log("Connection terminated unexpectedly");
  }
});
CloseEvent
object

error

Fired when an error occurs on the WebSocket connection.
socket.addEventListener("error", (event) => {
  console.error("WebSocket error occurred");
});
ErrorEvent
Event
A standard Event object with no additional properties.

References