getWsServerDurableObjectFetch
The getWsServerDurableObjectFetch
function returns a convenient handler for a Cloudflare worker to route requests to the fetch handler of a WsServerDurableObject
for the given namespace.
getWsServerDurableObjectFetch<Namespace>(namespace: Namespace): (request: Request, env: {[namespace in Namespace]: DurableObjectNamespace<WsServerDurableObject>}) => Response
Type | Description | |
---|---|---|
namespace | Namespace | A string for the namespace of the Durable Objects that you want this worker to route requests to. |
returns | (request: Request, env: {[namespace in Namespace]: DurableObjectNamespace<WsServerDurableObject>}) => Response | A fetch handler that routes WebSocket upgrade requests to a Durable Object. |
The implementation of the function that this returns requires the request to be a WebSocket 'Upgrade' request, and for the client to have provided a sec-websocket-key
header that the server can use as a unique key for the client.
It then takes the path of the HTTP request and routes the upgrade request to a Durable Object (in the given namespace) for that path. From then on, the Durable Object handles all the WebSocket communication.
Note that you'll need to have a Wrangler configuration that connects your Durable Object class to the namespace. In other words, you'll have something like this in your wrangler.toml
file.
[[durable_objects.bindings]]
name = "MyDurableObjects"
class_name = "MyDurableObject"
Note that it is not required to use this handler to route TinyBase client requests in your Cloudflare app. If you have your own custom routing logic, path scheme, or authentication, for example, you can easily implement that in the worker's fetch method yourself. See the Durable Objects documentation for examples.
You can also pass a newly created request to the Durable Object's fetch
method. For example, you can overwrite the 'path' that the Durable Object thinks it is serving, perhaps to inject a unique authenticated user Id
that wasn't actually provided by the client WebSocket.
Example
This example sets up default routing of the WebSocket upgrade request to a Durable Object in the MyDurableObjects
namespace. This would require the wrangler.toml
configuration shown above.
import {
WsServerDurableObject,
getWsServerDurableObjectFetch,
} from 'tinybase/synchronizers/synchronizer-ws-server-durable-object';
export class MyDurableObject extends WsServerDurableObject {}
export default {fetch: getWsServerDurableObjectFetch('MyDurableObjects')};
Since
v5.4.0