Cloudflare Docs
Durable Objects
Edit this page
Report an issue with this page
Log into the Cloudflare dashboard
Set theme to dark (⇧+D)


​​ Background

WebSockets are long-lived TCP connections that enable bi-directional, real-time communication between client and server.

Durable Objects support the Workers Runtime WebSocket API. Your Durable Object can act as a single point-of-coordination for WebSocket sessions, giving you full control over messages sent to and from clients, allowing you to build applications like chat rooms and multiplayer games.

For more information beyond the API reference, refer to the Build a WebSocket server example.

​​ WebSocket Hibernation API

In addition to Workers WebSocket API, Durable Objects WebSocket Hibernation API includes the below extensions to standard WebSocket API, state methods, and handler methods.

The WebSocket Hibernation API allows a Durable Object that is not currently running an event handler (such as handling a WebSocket message, HTTP request, or alarms) to be removed from memory while keeping its WebSockets connected (“hibernation”). This reduces duration charges that would otherwise be incurred during periods of inactivity.

To learn more about WebSocket Hibernation, refer to Build a WebSocket server with WebSocket Hibernation example.

​​ Extensions to WebSocket API

​​ serializeAttachment

  • serializeAttachment(valueany) : void

    • Keeps a copy of value in memory (not on disk) to survive hibernation. The value can be any type supported by the structured clone algorithm, which is true of most types.

    • If you modify value after calling this method, those changes will not be retained unless you call this method again. The serialized size of value is limited to 2,048 bytes, otherwise this method will throw an error. If you need larger values to survive hibernation, use the Transactional Storage API and pass the corresponding key to this method so it can be retrieved later.

​​ deserializeAttachment

  • deserializeAttachment() : any

    • Retrieves the most recent value passed to serializeAttachment(), or null if none exists.

​​ State Methods

​​ acceptWebSocket

  • acceptWebSocket(wsWebSocket, tagsArray<string>optional) : void

    • Adds a WebSocket to the set attached to this Durable Object. ws.accept() must not have been called separately. Once called, any incoming messages will be delivered by calling the Durable Object’s webSocketMessage() handler, and webSocketClose() will be invoked upon disconnect.

    • After calling state.acceptWebSocket(ws), the WebSocket is accepted. Therefore, you can use its send() and close() methods to send messages. Its addEventListener() method will not ever receive any events as they will be delivered to the Durable Object.

    • tags are optional string tags used to look up the WebSocket with state.getWebSockets(). Each tag is limited to 256 characters, and each WebSocket is limited to 10 tags associated with it.

    • The WebSocket Hibernation API permits a maximum of 32,768 WebSocket connections per Durable Object instance, but the CPU and memory usage of a given workload may further limit the practical number of simultaneous connections.

​​ getWebSockets

  • getWebSockets(tagstringoptional) : Array<WebSocket>

    • Gets an array of accepted WebSockets matching the given tag. Disconnected WebSockets 1 are automatically removed from the list. Calling state.getWebSockets() with no tag argument will return all WebSockets.

    • 1 state.getWebSockets() may still return websockets even after ws.close() has been called. For example, if your server-side WebSocket (the Durable Object) sends a close, but does not receive one back (and has not detected a disconnect from the client), then the connection is in the CLOSING “readyState”. The client might send more messages, so the WebSocket is technically not disconnected.

​​ getTags

  • getTags(wsWebSocket) : Array<string>

    • Returns an Array of tags associated with the given WebSocket. Throws an error if you have not called state.acceptWebSocket() on the given WebSocket.

​​ setWebSocketAutoResponse

  • setWebSocketAutoResponse(webSocketRequestResponsePairWebSocketRequestResponsePairoptional): void

    • Sets an application level auto response that does not wake hibernated WebSockets.

    • state.setWebSocketAutoResponse receives WebSocketRequestResponsePair(requeststring, responsestring) as an argument, enabling any WebSocket that was accepted via state.acceptWebSocket() belonging to this Object to automatically reply with response when it receives the specified request.

    • state.setWebSocketAutoResponse() is preferable to setting up a server for static ping/pong messages because state.setWebSocketAutoResponse() handles application level ping/pongs without waking the WebSocket from hibernation, preventing unnecessary duration charges.

    • Both request and response are limited to 2,048 characters each.

    • If state.setWebSocketAutoResponse() is set without any argument, it will remove any previously set auto-response configuration. Setting state.setWebSocketAutoResponse() without any argument will stop a Durable Object from replying with response for a request. It will also stop updating the last timestamp of a request, but if there was any auto-response timestamp set, it will remain accessible with state.getWebSocketAutoResponseTimestamp().

​​ getWebSocketAutoResponse

  • getWebSocketAutoResponse() : Object | null

    • Gets the WebSocketRequestResponsePair(requeststring, responsestring) currently set, or null if there is none.

    • Each WebSocketRequestResponsePair(requeststring, responsestring) Object provides methods for getRequest() and getResponse().

​​ getWebSocketAutoResponseTimestamp

  • getWebSocketAutoResponseTimestamp(wsWebSocket) : Date | null

    • Gets the most recent Date when the WebSocket received an auto-response request, or null if the given WebSocket never received an auto-response request.

​​ setHibernatableWebSocketEventTimeout

  • setHibernatableWebSocketEventTimeout(timeoutnumberoptional) : void

    • Sets the maximum amount of milliseconds a WebSocket event (refer to the handler methods below) can run for.
    • If 0, or no value is given for the timeout, the previously set timeout (if any) will be unset.
    • The maximum value of timeout is 604,800,000 ms (7 days).

​​ getHibernatableWebSocketEventTimeout

  • getHibernatableWebSocketEventTimeout() : number | null

    • Gets the currently set hibernatable WebSocket event timeout if any had been set with state.setHibernatableWebSocketEventTimeout().

​​ Handler Methods

​​ webSocketMessage

  • webSocketMessage(wsWebSocket, messageString | ArrayBuffer) : void

​​ webSocketClose

  • webSocketClose(wsWebSocket, codenumber, reasonstring, wasCleanboolean) : void

    • Called by the system when a WebSocket is closed. wasClean() is true if the connection closed cleanly, false otherwise.

    • This method can be async.

​​ webSocketError

  • webSocketError(wsWebSocket, errorany) : void

    • Called by the system when any non-disconnection related errors occur.

    • This method can be async.