Cloudflare Docs
Workers
Workers
Visit Workers on GitHub
Set theme to dark (⇧+D)

WebSockets

​​ Background

WebSockets allow you to communicate in real time with your Cloudflare Workers serverless functions.

When using WebSockets with Durable Objects, we recommend using the Hibernatable WebSockets API which adds additional extensions to the standard WebSocket object.

​​ Constructor


// { 0: <WebSocket>, 1: <WebSocket> }
let websocketPair = new WebSocketPair();

The WebSocketPair returned from this constructor is an Object, with two WebSockets at keys 0 and 1.

These WebSockets are commonly referred to as client and server. The below example combines Object.values and ES6 destructuring to retrieve the WebSockets as client and server:


let [client, server] = Object.values(new WebSocketPair());

​​ Methods

​​ accept

  • accept()

    • Accepts the WebSocket connection and begins terminating requests for the WebSocket on Cloudflare’s global network. This effectively enables the Workers runtime to begin responding to and handling WebSocket requests.

​​ addEventListener

  • addEventListener(eventWebSocketEvent, callbackFunctionFunction)

    • Add callback functions to be executed when an event has occurred on the WebSocket.

​​ Parameters

  • event WebSocketEvent

    • The WebSocket event (refer to Events) to listen to.
  • callbackFunction(message Message ) Function

    • A function to be called when the WebSocket responds to a specific event.

​​ close

  • close(codenumber, reasonstring)

    • Close the WebSocket connection.

​​ Parameters

  • codeinteger optional

  • reasonstring optional

    • A human-readable string indicating why the WebSocket connection was closed.

​​ send

  • send(messagestring | ArrayBuffer | ArrayBufferView)

    Send a message to the other WebSocket in this WebSocket pair.

​​ Parameters

  • messagestring

    • The message to send down the WebSocket connection to the corresponding client. This should be a string or something coercible into a string; for example, strings and numbers will be simply cast into strings, but objects and arrays should be cast to JSON strings using JSON.stringify, and parsed in the client.

​​ Events

  • close

    • An event indicating the WebSocket has closed.
  • error

    • An event indicating there was an error with the WebSocket.
  • message

    • An event indicating a new message received from the client, including the data passed by the client.

​​ Types

​​ Message

  • data any - The data passed back from the other WebSocket in your pair.
  • type string - Defaults to message.