new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Cloudflare Workers · Runtime APIs · all subjects

websockets

23 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

WebSocketPair constructor creates bidirectional pair

The WebSocketPair constructor creates an object containing two WebSockets at keys 0 and 1. These can be retrieved as client and server using Object.values and ES6 destructuring: let [client, server] = Object.values(new WebSocketPair());

accept() method accepts WebSocket connection

The accept(options?) method accepts the WebSocket connection and begins terminating requests on Cloudflare's global network, enabling the Workers runtime to respond to and handle WebSocket requests.

accept() allowHalfOpen option for WebSocket proxying

The accept() method accepts an options object with an allowHalfOpen boolean property (optional, defaults to false). When true, the runtime will not automatically send a reciprocal Close frame when receiving a Close frame from the peer. Instead, readyState remains CLOSING until close() is explicitly called. This is useful for WebSocket proxying where you need to coordinate the close across both sides of the proxy.

addEventListener() attaches event handlers to WebSocket

The addEventListener(event, callbackFunction) method adds callback functions to be executed when an event occurs on the WebSocket. It takes a WebSocketEvent and a Function that receives a Message object.

close() method closes WebSocket connection

The close(code?, reason?) method closes the WebSocket connection. The code parameter is an optional integer indicating the close code sent by the server, matching options from the WebSocket spec status codes list. The reason parameter is an optional human-readable string indicating why the connection was closed.

send() method sends message over WebSocket

The send(message) method sends a message to the other WebSocket in the pair. The message parameter accepts a string, ArrayBuffer, or ArrayBufferView. Strings and numbers are cast to strings, while objects and arrays should be cast to JSON strings using JSON.stringify and parsed on the client.

readyState property indicates WebSocket connection state

The readyState property returns the current state of the WebSocket connection as a number. Possible values are: WebSocket.CONNECTING (0) - connection not yet open, WebSocket.OPEN (1) - connection open and ready, WebSocket.CLOSING (2) - connection in process of closing, WebSocket.CLOSED (3) - connection closed.

binaryType property controls binary frame handling

The binaryType property is a string that controls how binary frames received on the WebSocket are surfaced to the message event. Valid values are "blob" and "arraybuffer". The value is consulted when each incoming binary frame is dispatched, so assigning a new value affects only subsequent messages. The default is controlled by the websocket_standard_binary_type compatibility flag.

WebSocket events: close, error, message

WebSockets support three events: close (fired when WebSocket closes, includes code, reason, and wasClean properties), error (fired when there is an error), and message (fired when a new message is received from the client).

Message event object structure

The Message event object contains: data (any) - the data passed back from the other WebSocket in the pair, and type (string) - defaults to "message".

WebSocket message size limit 32 MiB

WebSocket messages received by a Worker have a size limit of 32 MiB (33,554,432 bytes). If a larger message is sent, the WebSocket will be automatically closed with a 1009 "Message is too large" response.

web_socket_auto_reply_to_close compatibility flag auto-replies to Close frames

With the web_socket_auto_reply_to_close compatibility flag (enabled by default on compatibility dates on or after 2026-04-07), the Workers runtime automatically sends a reciprocal Close frame when it receives a Close frame from the peer. The readyState transitions to CLOSED before the close event fires, matching the WebSocket specification and standard browser behavior. If close() is called inside the close event handler, the call is silently ignored.

allowHalfOpen mode example for WebSocket proxying

Example of WebSocket proxying with allowHalfOpen: server.accept({ allowHalfOpen: true }); server.addEventListener("close", (event) => { console.log(server.readyState); // WebSocket.CLOSING - gives time to coordinate close on the other side. server.close(event.code, "done"); });

web_socket_manual_reply_to_close prior behavior before 2026-04-07

On compatibility dates before 2026-04-07 (or with the web_socket_manual_reply_to_close flag), receiving a Close frame leaves the WebSocket in CLOSING state and code must call close() to complete the handshake. Failing to do so can result in 1006 abnormal closure errors on the client.

websocket_standard_binary_type compatibility flag changes default binaryType

With the websocket_standard_binary_type compatibility flag (enabled by default on compatibility dates on or after 2026-03-17), binaryType defaults to "blob" and binary frames are delivered as Blob objects, matching the WebSocket specification and standard browser behavior. Without the flag, binaryType defaults to "arraybuffer" and binary frames are delivered as ArrayBuffer.

Binary frame buffering and message event dispatch

An incoming binary frame is fully buffered before the message event fires, regardless of binaryType. The choice between Blob and ArrayBuffer does not change when or whether the frame is received — only how you access its bytes.

arraybuffer vs blob data access synchronous vs asynchronous

With binaryType set to "arraybuffer", event.data is an ArrayBuffer and you can inspect its size and read bytes synchronously (for example, new Uint8Array(event.data)). With binaryType set to "blob", event.data is a Blob and reading bytes is asynchronous (for example, await event.data.arrayBuffer() or await event.data.bytes()).

Setting binaryType before accept() ensures consistent delivery type

The binaryType property is mutable and the value is consulted at the moment each binary frame is dispatched to the message event. To guarantee every binary message on a WebSocket is delivered as the same type, assign binaryType before calling accept() to ensure the setting is in place before the runtime starts dispatching incoming frames.

Example: opt back into ArrayBuffer delivery by setting binaryType before accept

Example showing how to opt back into ArrayBuffer delivery: const resp = await fetch("https://example.com", { headers: { Upgrade: "websocket" } }); const ws = resp.webSocket; ws.binaryType = "arraybuffer"; ws.accept(); ws.addEventListener("message", (event) => { if (typeof event.data === "string") { // Text frame. } else { // event.data is an ArrayBuffer } });

no_websocket_standard_binary_type Wrangler config flag keeps ArrayBuffer default

To keep ArrayBuffer as the default for every WebSocket in a Worker instead of migrating to Blob, add the no_websocket_standard_binary_type flag to the Wrangler configuration file. Individual WebSockets can still override the default by assigning binaryType. This flag has no effect on the Durable Object hibernatable WebSocket webSocketMessage handler, which always receives binary data as ArrayBuffer.

WebSockets with Durable Objects for multi-connection coordination

If an application needs to coordinate among multiple WebSocket connections, such as a chat room or game match, clients should send messages to a single-point-of-coordination. Durable Objects provide this single-point-of-coordination for Cloudflare Workers and are often used in parallel with WebSockets to persist state over multiple clients and connections. The Durable Objects extended WebSockets API should be used in this case.

WebSocket created with new WebSocket(url) always auto-replies to Close frames

WebSockets created with new WebSocket(url) always auto-reply to Close frames after the web_socket_auto_reply_to_close flag takes effect. There is no way to pass allowHalfOpen because these WebSockets are automatically accepted. If half-open behavior is needed for a client WebSocket, use fetch() with the Upgrade: websocket header instead, then call resp.webSocket.accept({ allowHalfOpen: true }).

Example: close event handler with automatic close reply

Example of close event handler with automatic close reply enabled: server.addEventListener("close", (event) => { console.log(server.readyState); // WebSocket.CLOSED console.log(event.code); // 1000 console.log(event.wasClean); // true });

Give your agent this brain