Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ description: Build a WebSocket server using WebSocket Hibernation on Durable
Objects and Workers.
---

import { TabItem, Tabs, WranglerConfig } from "~/components";
import { TabItem, Tabs, WranglerConfig, TypeScriptExample } from "~/components";

This example is similar to the [Build a WebSocket server](/durable-objects/examples/websocket-server/) example, but uses the WebSocket Hibernation API. The WebSocket Hibernation API should be preferred for WebSocket server applications built on Durable Objects, since it significantly decreases duration charge, and provides additional features that pair well with WebSocket applications. For more information, refer to [Use Durable Objects with WebSockets](/durable-objects/best-practices/websockets/).

Expand All @@ -22,84 +22,7 @@ WebSocket Hibernation is unavailable for outgoing WebSocket use cases. Hibernati

:::

<Tabs> <TabItem label="JavaScript" icon="seti:javascript">

```js
import { DurableObject } from "cloudflare:workers";

// Worker
export default {
async fetch(request, env, ctx) {
if (request.url.endsWith("/websocket")) {
// Expect to receive a WebSocket Upgrade request.
// If there is one, accept the request and return a WebSocket Response.
const upgradeHeader = request.headers.get("Upgrade");
if (!upgradeHeader || upgradeHeader !== "websocket") {
return new Response("Durable Object expected Upgrade: websocket", {
status: 426,
});
}

// This example will refer to the same Durable Object,
// since the name "foo" is hardcoded.
let id = env.WEBSOCKET_HIBERNATION_SERVER.idFromName("foo");
let stub = env.WEBSOCKET_HIBERNATION_SERVER.get(id);

return stub.fetch(request);
}

return new Response(null, {
status: 400,
statusText: "Bad Request",
headers: {
"Content-Type": "text/plain",
},
});
},
};

// Durable Object
export class WebSocketHibernationServer extends DurableObject {
async fetch(request) {
// Creates two ends of a WebSocket connection.
const webSocketPair = new WebSocketPair();
const [client, server] = Object.values(webSocketPair);

// Calling `acceptWebSocket()` informs the runtime that this WebSocket is to begin terminating
// request within the Durable Object. It has the effect of "accepting" the connection,
// and allowing the WebSocket to send and receive messages.
// Unlike `ws.accept()`, `state.acceptWebSocket(ws)` informs the Workers Runtime that the WebSocket
// is "hibernatable", so the runtime does not need to pin this Durable Object to memory while
// the connection is open. During periods of inactivity, the Durable Object can be evicted
// from memory, but the WebSocket connection will remain open. If at some later point the
// WebSocket receives a message, the runtime will recreate the Durable Object
// (run the `constructor`) and deliver the message to the appropriate handler.
this.ctx.acceptWebSocket(server);

return new Response(null, {
status: 101,
webSocket: client,
});
}

async webSocketMessage(ws, message) {
// Upon receiving a message from the client, reply with the same message,
// but will prefix the message with "[Durable Object]: " and return the
// total number of connections.
ws.send(
`[Durable Object] message: ${message}, connections: ${this.ctx.getWebSockets().length}`,
);
}

async webSocketClose(ws, code, reason, wasClean) {
// If the client closes the connection, the runtime will invoke the webSocketClose() handler.
ws.close(code, "Durable Object is closing WebSocket");
}
}
```

</TabItem> <TabItem label="TypeScript" icon="seti:typescript">

<TypeScriptExample>
```ts
import { DurableObject } from "cloudflare:workers";

Expand Down Expand Up @@ -185,8 +108,7 @@ export class WebSocketHibernationServer extends DurableObject {
}
}
```

</TabItem> </Tabs>
</TypeScriptExample>

Finally, configure your Wrangler file to include a Durable Object [binding](/durable-objects/get-started/#4-configure-durable-object-bindings) and [migration](/durable-objects/reference/durable-objects-migrations/) based on the namespace and class name chosen previously.

Expand Down
91 changes: 3 additions & 88 deletions src/content/docs/durable-objects/examples/websocket-server.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ sidebar:
description: Build a WebSocket server using Durable Objects and Workers.
---

import { TabItem, Tabs, GlossaryTooltip, WranglerConfig } from "~/components";
import { TabItem, Tabs, GlossaryTooltip, WranglerConfig, TypeScriptExample } from "~/components";

This example shows how to build a WebSocket server using <GlossaryTooltip term="Durable Object">Durable Objects</GlossaryTooltip> and Workers. The example exposes an endpoint to create a new WebSocket connection. This WebSocket connection echos any message while including the total number of WebSocket connections currently established. For more information, refer to [Use Durable Objects with WebSockets](/durable-objects/best-practices/websockets/).

Expand All @@ -20,91 +20,7 @@ WebSocket connections pin your Durable Object to memory, and so duration charges

:::

<Tabs> <TabItem label="JavaScript" icon="seti:javascript">

```js
import { DurableObject } from "cloudflare:workers";

// Worker
export default {
async fetch(request, env, ctx) {
if (request.url.endsWith("/websocket")) {
// Expect to receive a WebSocket Upgrade request.
// If there is one, accept the request and return a WebSocket Response.
const upgradeHeader = request.headers.get("Upgrade");
if (!upgradeHeader || upgradeHeader !== "websocket") {
return new Response("Durable Object expected Upgrade: websocket", {
status: 426,
});
}

// This example will refer to the same Durable Object,
// since the name "foo" is hardcoded.
let id = env.WEBSOCKET_SERVER.idFromName("foo");
let stub = env.WEBSOCKET_SERVER.get(id);

return stub.fetch(request);
}

return new Response(null, {
status: 400,
statusText: "Bad Request",
headers: {
"Content-Type": "text/plain",
},
});
},
};

// Durable Object
export class WebSocketServer extends DurableObject {
currentlyConnectedWebSockets;

constructor(ctx, env) {
// This is reset whenever the constructor runs because
// regular WebSockets do not survive Durable Object resets.
//
// WebSockets accepted via the Hibernation API can survive
// a certain type of eviction, but we will not cover that here.
super(ctx, env);
this.currentlyConnectedWebSockets = 0;
}

async fetch(request) {
// Creates two ends of a WebSocket connection.
const webSocketPair = new WebSocketPair();
const [client, server] = Object.values(webSocketPair);

// Calling `accept()` tells the runtime that this WebSocket is to begin terminating
// request within the Durable Object. It has the effect of "accepting" the connection,
// and allowing the WebSocket to send and receive messages.
server.accept();
this.currentlyConnectedWebSockets += 1;

// Upon receiving a message from the client, the server replies with the same message,
// and the total number of connections with the "[Durable Object]: " prefix
server.addEventListener("message", (event) => {
server.send(
`[Durable Object] currentlyConnectedWebSockets: ${this.currentlyConnectedWebSockets}`,
);
});

// If the client closes the connection, the runtime will close the connection too.
server.addEventListener("close", (cls) => {
this.currentlyConnectedWebSockets -= 1;
server.close(cls.code, "Durable Object is closing WebSocket");
});

return new Response(null, {
status: 101,
webSocket: client,
});
}
}
```

</TabItem> <TabItem label="TypeScript" icon="seti:typescript">

<TypeScriptExample>
```ts
import { DurableObject } from "cloudflare:workers";

Expand Down Expand Up @@ -189,8 +105,7 @@ export class WebSocketServer extends DurableObject {
}
}
```

</TabItem> </Tabs>
</TypeScriptExample>

Finally, configure your Wrangler file to include a Durable Object [binding](/durable-objects/get-started/#4-configure-durable-object-bindings) and [migration](/durable-objects/reference/durable-objects-migrations/) based on the <GlossaryTooltip term="namespace">namespace</GlossaryTooltip> and class name chosen previously.

Expand Down