With Cloudflare Durable Objects, how does a chat-room object accept a client WebSocket through the Hibernation API and receive its messages?
answer
- a Worker forwards the upgrade
- two ends from one pair
- the runtime takes the server end
- class methods, not listeners
- status 101 carries the client end
basics
~20 sThe Worker forwards the upgrade request to the object's stub; the object creates a WebSocketPair, passes the server end to this.ctx.acceptWebSocket(), and returns a 101 response carrying the client end. Messages then arrive at its webSocketMessage() method.
solid answer
~40 sA client opens the WebSocket against a Worker, which checks the `Upgrade: websocket` header and forwards the request to the room's stub, for example `env.CHAT_ROOM.getByName(room).fetch(request)`. In the object's `fetch()`, `new WebSocketPair()` gives a client end and a server end; `this.ctx.acceptWebSocket(server)` hands the server end to the runtime, and the object returns `new Response(null, { status: 101, webSocket: client })`. From then on the runtime calls methods on the class: `webSocketMessage(ws, message)` for each message (a string, or an `ArrayBuffer` for binary), `webSocketClose(ws, code, reason, wasClean)` when the connection closes, and `webSocketError(ws, error)` for other failures. You never call `server.accept()` or `addEventListener()` on that socket. In `webSocketClose()`, call `ws.close(code, reason)`: before compatibility date 2026-04-07 that is what completes the close handshake, and on later dates the call is still safe.
code
javascript · 33 linesimport { DurableObject } from "cloudflare:workers";
export class ChatRoom extends DurableObject {
async fetch(request) {
const [client, server] = Object.values(new WebSocketPair());
this.ctx.acceptWebSocket(server);
return new Response(null, { status: 101, webSocket: client });
}
async webSocketMessage(ws, message) {
if (typeof message === "string") {
ws.send(`echo: ${message}`);
}
}
async webSocketClose(ws, code, reason, wasClean) {
ws.close(code, reason);
}
async webSocketError(ws, error) {
console.error("WebSocket error", error);
}
}
export default {
async fetch(request, env) {
if (request.headers.get("Upgrade") !== "websocket") {
return new Response("Expected Upgrade: websocket", { status: 426 });
}
const room = new URL(request.url).searchParams.get("room") ?? "lobby";
return env.CHAT_ROOM.getByName(room).fetch(request);
},
};go deeper
Recall the five steps in order: the Worker checks Upgrade, forwards to the stub, the object creates a WebSocketPair, calls this.ctx.acceptWebSocket(server) and returns 101 with the client end.
Explain that after acceptWebSocket() the runtime, not your code, owns the server end and calls webSocketMessage, webSocketClose and webSocketError as class methods.
Show that you know the close handshake depends on the compatibility date, that a dropped client still reaches webSocketClose() with 1006, and where cleanup belongs.
Speak to where validation and authentication of the upgrade belong: in the Worker, before a Durable Object request is spent, with the room chosen by name.
## The pieces involved A WebSocket served by a Durable Object passes through two pieces of code, and each has its own job. - **The Worker** is the public entry point. Its `fetch(request, env)` handler receives the client's HTTP request carrying `Upgrade: websocket`, decides which room it belongs to and forwards it. - **The stub** is the Worker's handle on one Durable Object instance. `env.CHAT_ROOM.getByName(room)` returns the stub for the object with that name, and `stub.fetch(request)` delivers the request to it. - **The Durable Object class**, here `ChatRoom extends DurableObject` imported from `cloudflare:workers`, holds every socket of the room. - **`WebSocketPair`** is a runtime constructor that creates two connected `WebSocket` ends. One end goes back to the client; the other stays with the object. - **`this.ctx`** is the object's `DurableObjectState`, and its `acceptWebSocket()` method is the entry point to the Hibernation API. ## The accept sequence 1. The Worker checks `request.headers.get("Upgrade")` and answers anything that is not a WebSocket upgrade itself, commonly with status 426, so no Durable Object request is spent on it. 2. The Worker forwards the request: `return env.CHAT_ROOM.getByName(room).fetch(request)`. 3. In the object's `fetch()`, `const [client, server] = Object.values(new WebSocketPair())` creates the two ends. 4. `this.ctx.acceptWebSocket(server)` attaches the server end to the object. From this point the runtime owns that end: it keeps the connection open and dispatches its events to the class. 5. The object returns `new Response(null, { status: 101, webSocket: client })`. Status 101 completes the handshake, and the `webSocket` field hands the client end back through the Worker to the caller. `acceptWebSocket()` also takes an optional array of tags, used later to find groups of sockets; the basic flow does not need them. Because the Worker sits in front of the object, it is also the place to authenticate the upgrade, for example by checking a cookie or token before forwarding, and to pick the room name from the URL. The object then only ever sees requests it should accept. ## The handler methods After `acceptWebSocket()`, nothing is wired with `addEventListener()`. The runtime calls methods defined on the class, and it does so even if the object was evicted from memory in between, which is the point of the API. | Method | Called when | Arguments | |---|---|---| | `webSocketMessage` | a data message arrives | `ws`, `message` (a `string` for text, an `ArrayBuffer` for binary) | | `webSocketClose` | the connection closes | `ws`, `code`, `reason`, `wasClean` | | `webSocketError` | a non-disconnection error occurs | `ws`, `error` | - `ws` is the server end that received the event, so a reply is simply `ws.send(...)`. - Control frames never reach `webSocketMessage()`; the runtime answers a protocol Ping on its own. - All three methods may be `async`. - If the client vanishes without a Close frame, `webSocketClose()` still runs, with code `1006` and `wasClean` set to `false`. ## Closing the socket The close handshake depends on the Worker's compatibility date. On dates before 2026-04-07 the object must answer a client's Close frame itself, by calling `ws.close(code, reason)` in `webSocketClose()`; skipping it leaves the client reporting an abnormal closure (`1006`). From 2026-04-07 the `web_socket_auto_reply_to_close` compatibility flag is on by default and is documented to send the reciprocal Close frame for you, with a second `close()` call silently ignored. Calling `ws.close(code, reason)` in the handler is therefore correct on every date, and it is the safe habit to keep. The `code` argument is the close code the peer sent, such as `1000` for a normal closure or `1001` for going away, and `reason` may be an empty string. Anything the object tracks per client, such as presence in a room, should be cleaned up here, because this is the last event that socket produces. ## Mistakes that break the wiring - **Calling `server.accept()` as well.** That is the standard API; once a socket has been accepted that way, `acceptWebSocket()` throws. - **Returning the `server` end in the 101 response.** The object keeps `server`; only `client` goes back. - **Expecting `server.addEventListener("message", ...)` to fire.** Events of a hibernatable socket go to the class methods instead. - **Expecting `fetch()` to run per message.** It runs once, for the upgrade request. - **Forgetting the configuration.** The class needs a `durable_objects` binding and a migration that creates it, which for a new class is `new_sqlite_classes`. Everything else in the Hibernation API, from tags to attachments to auto-responses, builds on exactly this skeleton: one Worker that routes, one object that accepts, and three class methods that the runtime calls.
- Why does the Worker check the Upgrade header instead of letting the Durable Object reject bad requests?Workers and Durable Objects are both billed per request, so a request the object can never accept still costs a Durable Object request if it gets that far. Rejecting it in the Worker, typically with status 426, avoids that charge and keeps the object's `fetch()` focused on accepting sockets.
- If a client's network drops without a Close frame, which handler runs, and with what?`webSocketClose()` still runs, with code `1006`, `wasClean` set to `false` and a reason saying the socket disconnected without sending a Close frame. `webSocketError()` is for other, non-disconnection failures. Put per-client cleanup in `webSocketClose()` so both a clean close and a dropped connection reach it.
- Expects server.addEventListener("message") to fire after ctx.acceptWebSocket() took the socket.
- Returns the server end of the WebSocketPair in the 101 response instead of the client end.
- Thinks every incoming WebSocket message calls the object's fetch() method again.
- Accepts the upgrade with a 200 response and the socket in a header.
- Lets the Durable Object reject non-upgrade requests, paying a request for each.
Assumes compatibility dates from 2026-04-07, where web_socket_auto_reply_to_close is on by default; on earlier dates webSocketClose() must call ws.close() to finish the close handshake.