Course lesson 41 · Advanced Durable Objects
Setting up Websockets
This lesson replaces the tracker’s temporary JSON response with a WebSocket handshake. It introduces the object’s message, close, and error handlers, then explains how one connection can receive a response or how all connected clients can receive a broadcast. The surrounding Hono route forwards the incoming request to the selected account object.
Primary source: course video 41 · Supplied English subtitles · 00:08:50.
Understand the idea
- A WebSocket establishes a persistent, two-way channel between browser and server.
- The object’s event handlers receive connection lifecycle events rather than ordinary independent HTTP requests.
- The context can enumerate accepted sockets, allowing a message to be broadcast to every connected viewer.
- A WebSocketPair supplies client and server ends; the server end is accepted by the object and the client end is returned in the upgrade response.
- The handshake response uses status 101 to switch protocols.
What the course does
- Review message, close, and error handlers on the Durable Object class.
- Explore echoing a received message and broadcasting to all registered sockets.
- Create a WebSocket pair inside fetch and accept the server endpoint through the object context.
- Return the client endpoint with the protocol upgrade response.
- Adapt the Hono socket route to identify the account from a request header and proxy to its object.
Watch for
- The lesson discusses checking the Upgrade header but does not present this explanation as a complete authentication implementation.
- Account selection is still scaffolding; later lessons place authenticated account selection in the user application’s server.
- Added advice: status 101 means Switching Protocols; it does not guarantee a connection can never close.
Recall before revealing
Which end of a WebSocketPair remains associated with the Durable Object?
Reveal the explanation
The server end is accepted by the object; the client end is returned to establish the browser’s connection.
Try it
Trace an incoming message through an echo implementation and then through a broadcast implementation.
Check your result
You distinguish sending to the originating socket from iterating over every accepted socket.
Practice prompts and answer checks are added teaching material. Answer from memory first, then compare and explain any difference.
Rewatch only what you need
Open this lesson in your original course library and seek to the times below. Videos are not hosted on this site.
- 00:00:45 — Durable Object WebSocket handlers
- 00:03:22 — Enumerating connected sockets
- 00:05:12 — Creating a WebSocket pair
- 00:08:07 — Selecting an account through headers
Companion primary documentation: Durable Objects WebSockets. For recorded API names, commands, limits, and prices, check the version you use.