WebSockets
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.
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.
-
serializeAttachment(value any )
: 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 ofvalue
is limited to 2,048 bytes, otherwise this method will throw an error. If you need larger values to survive hibernation, use the Storage API and pass the corresponding key to this method so it can be retrieved later.
-
-
deserializeAttachment()
: any- Retrieves the most recent value passed to
serializeAttachment()
, ornull
if none exists.
- Retrieves the most recent value passed to
-
acceptWebSocket(ws WebSocket , tags Array<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’swebSocketMessage()
handler, andwebSocketClose()
will be invoked upon disconnect. -
After calling
state.acceptWebSocket(ws)
, the WebSocket is accepted. Therefore, you can use itssend()
andclose()
methods to send messages. ItsaddEventListener()
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 withstate.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, but the CPU and memory usage of a given workload may further limit the practical number of simultaneous connections.
-
-
getWebSockets(tag string optional)
: 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 notag
argument will return all WebSockets. -
1
state.getWebSockets()
may still return websockets even afterws.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 theCLOSING
“readyState”. The client might send more messages, so the WebSocket is technically not disconnected.
-
-
getTags(ws WebSocket )
: 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.
- Returns an Array of tags associated with the given WebSocket. Throws an error if you have not called
-
setWebSocketAutoResponse(webSocketRequestResponsePair WebSocketRequestResponsePair optional)
: void-
Sets an application level auto response that does not wake hibernated WebSockets.
-
state.setWebSocketAutoResponse
receivesWebSocketRequestResponsePair(request string , response string )
as an argument, enabling any WebSocket that was accepted viastate.acceptWebSocket()
belonging to this Object to automatically reply withresponse
when it receives the specifiedrequest
. -
state.setWebSocketAutoResponse()
is preferable to setting up a server for static ping/pong messages becausestate.setWebSocketAutoResponse()
handles application level ping/pongs without waking the WebSocket from hibernation, preventing unnecessary duration charges. -
Both
request
andresponse
are limited to 2,048 characters each. -
If
state.setWebSocketAutoResponse()
is set without any argument, it will remove any previously set auto-response configuration. Settingstate.setWebSocketAutoResponse()
without any argument will stop a Durable Object from replying withresponse
for arequest
. It will also stop updating the last timestamp of arequest
, but if there was any auto-response timestamp set, it will remain accessible withstate.getWebSocketAutoResponseTimestamp()
.
-
-
getWebSocketAutoResponse()
: Object | null-
Gets the
WebSocketRequestResponsePair(request string , response string )
currently set, ornull
if there is none. -
Each
WebSocketRequestResponsePair(request string , response string )
Object provides methods forgetRequest()
andgetResponse()
.
-
-
getWebSocketAutoResponseTimestamp(ws WebSocket )
: Date | null- Gets the most recent
Date
when the WebSocket received an auto-response request, ornull
if the given WebSocket never received an auto-response request.
- Gets the most recent
-
setHibernatableWebSocketEventTimeout(timeout number optional)
: 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 thetimeout
, the previously set timeout (if any) will be unset. -
The maximum value of
timeout
is 604,800,000 ms (7 days).
-
-
getHibernatableWebSocketEventTimeout()
: number | null- Gets the currently set hibernatable WebSocket event timeout if any had been set with
state.setHibernatableWebSocketEventTimeout()
.
- Gets the currently set hibernatable WebSocket event timeout if any had been set with
-
webSocketMessage(ws WebSocket , message string | ArrayBuffer )
: void-
Called by the system when an accepted WebSocket receives a message.
-
This method can be
async
. -
This method is not called for WebSocket control frames. The system will respond to an incoming WebSocket protocol ping ↗ automatically without interrupting hibernation.
-
-
webSocketClose(ws WebSocket , code number ,reason string , wasClean boolean )
: 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(ws WebSocket , error any )
: void-
Called by the system when any non-disconnection related errors occur.
-
This method can be
async
.
-
- Refer to Build a WebSocket server to learn more about building a WebSocket server using Durable Objects and Workers.
- For more information beyond the API reference Durable Objects with WebSockets.
- Mozilla Developer Network’s (MDN) documentation on the WebSocket class ↗.
- Cloudflare’s WebSocket template for building applications on Workers using WebSockets ↗.