# Add WebSockets to a Cloudflare Worker with Durable Objects

Yes. An agent reads your Worker and wrangler config, adds a WebSocket endpoint on a Durable Object with hibernation, and tests it with Vitest in the Workers runtime.

[Run this on Rush](https://cloud.getrush.ai/run/add-websockets/cloudflare-workers/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the Worker as it is before adding a protocol to it. In a project started from the `hello-world-do-template` in cloudflare/templates, `src/index.ts` exports a `MyDurableObject` class extending `DurableObject<Env>` with one RPC method, `sayHello`, that runs a one-row `SELECT` on `this.ctx.storage.sql` and returns the greeting, and a default `fetch` handler that derives a `DurableObjectId` from the request pathname with `idFromName`, gets a stub and returns the greeting. `wrangler.json` declares the `MY_DURABLE_OBJECT` binding, a `migrations` entry with `new_sqlite_classes: ["MyDurableObject"]` tagged `v1`, `compatibility_date` set to `2025-10-08` and `observability.enabled: true`.

It reads `package.json` too: `wrangler` 4 and `typescript` 5.9 as the only dev dependencies, scripts `dev`, `deploy`, `cf-typegen` (`wrangler types`) and `check` (`tsc && wrangler deploy --dry-run`), and no test runner. `worker-configuration.d.ts` is generated by `wrangler types` and already types `MY_DURABLE_OBJECT` as a `DurableObjectNamespace` of the class, so any new binding or class name has to be followed by `npm run cf-typegen` to keep the types honest.

The agent adds a `/ws` route to the `fetch` handler that checks for `Upgrade: websocket`, picks the Durable Object by a room name from the URL and forwards the request to it. In the class it adds a `fetch` method that creates a `WebSocketPair`, calls `this.ctx.acceptWebSocket(server)` so the object can hibernate between messages, and returns the client end with status `101`. It implements `webSocketMessage` to broadcast each message to `this.ctx.getWebSockets()`, `webSocketClose` to close cleanly, and `webSocketError`, and keeps the existing `sayHello` RPC and SQL storage untouched. Because the class already exists in `migrations`, no new migration is needed; when the prompt asks for a second class, it adds a `v2` migration instead of editing `v1`.

For proof it adds `@cloudflare/vitest-pool-workers` and `vitest` as dev dependencies, a `vitest.config.ts` using `defineWorkersConfig` with `wrangler: { configPath: "./wrangler.json" }` as other templates in the same repository do, and a test that calls the Worker with an upgrade request, asserts the `101`, sends a message over the returned socket and reads it back. It runs `npm run cf-typegen`, `npm run check` and `npx vitest run` in its sandbox, opens the pull request and reads any workflow on it, fixing what fails.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add a WebSocket endpoint to this Cloudflare Worker using its Durable Object. Read src/index.ts, wrangler.json, package.json and worker-configuration.d.ts first. Add a /ws route that upgrades the connection and forwards it to a Durable Object chosen by a room name in the URL. In the Durable Object class use the hibernation API: accept the server socket with ctx.acceptWebSocket, implement webSocketMessage to broadcast to every connected socket, and webSocketClose and webSocketError. Keep the existing RPC method and storage. Do not edit an existing migration; add a new one only if a new class is needed. Add Vitest with @cloudflare/vitest-pool-workers and a test that upgrades, sends a message and reads it back. Run npm run cf-typegen, npm run check and the tests before you push. Open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request on a new branch that changes `src/index.ts` to add the `/ws` route and the WebSocket handlers on the Durable Object, `package.json` and the lockfile to add Vitest and the Workers pool, a new `vitest.config.ts`, a `test/` directory with the WebSocket test, and a regenerated `worker-configuration.d.ts` if a binding or class changed. In a project shaped like the Durable Objects starter, `wrangler.json` is unchanged because the class and its `v1` migration already exist. The description explains the room-name routing and why hibernation is used.

The proof is the Vitest run inside the Workers runtime, kept in the session's trajectory with its output, alongside the `tsc` and `wrangler deploy --dry-run` output from `npm run check`. Any workflow the repository already runs on pull requests runs here too. No deploy is claimed: `wrangler deploy` needs the account's credentials and is the reviewer's step after merging.

Before merging, a reviewer checks that broadcasting to every socket in the object is the right fan-out for their use, that the room name in the URL is validated the way they want, and whether messages should also be written to the object's SQL storage for late joiners. Then they run `npm run dev` or deploy to a preview and connect a client to `/ws`.

## Run it on every Linear issue labelled realtime

Add an automation in the Project with a `linear` trigger on issues labelled `realtime` and a prompt written like this one in general terms: read the Worker and its wrangler config, implement what the issue asks on the Durable Object with the hibernation API, add or extend the Vitest tests, and open a pull request. The trigger adds the issue after the prompt, so the agent reads the room model or message shape from the issue itself; nothing in `input` is substituted.

Each labelled issue starts one run in its own sandbox with its own pull request, and the link lands back on the issue. The automation has its own `max_runs_per_hour` cap, so a batch of labelled issues is spread out rather than refused. To start a single run by hand, send this request from a script with a fresh UUID as `request_id`.

## Why run it on Rush?

WebSockets on Workers are easy to get almost right: a handler that holds the socket in memory works in `wrangler dev` and then loses every connection when the object is evicted. On Rush the agent writes the hibernation version in its own sandbox, regenerates the types, runs `tsc` and a dry-run deploy, and tests the upgrade inside the real Workers runtime with the Vitest pool before the first push. Your machine never installs wrangler or a test runner.

The result is checkable. The test that upgrades and round-trips a message runs in the trajectory with its output, the type check and dry-run deploy are there too, and nothing is deployed or merged until a person says so. Because each run is independent, the same request can add a realtime endpoint to several Workers at once, one pull request each.

## Frequently asked questions

### Will it change my existing migrations or storage?

No. The prompt tells it not to edit an existing migration, and the `v1` entry with `new_sqlite_classes` stays as it is. The existing `sayHello` RPC and the SQL storage it uses are untouched. If the design needs a second Durable Object class, the agent adds a `v2` migration for it and says so in the pull request.

### Why the hibernation API rather than the standard WebSocket handlers?

Because `ctx.acceptWebSocket` lets the runtime evict the object from memory while sockets stay open and wake it on the next message, so idle rooms cost nothing and connections survive eviction. The handlers are `webSocketMessage`, `webSocketClose` and `webSocketError` on the class instead of event listeners on the socket. The agent explains this choice in the pull request.

### How is the WebSocket tested without a browser?

With `@cloudflare/vitest-pool-workers`, which runs Vitest inside the Workers runtime against your `wrangler.json`. The test sends a request with `Upgrade: websocket` to `/ws`, asserts the `101` response, takes the returned socket, sends a message and reads it back. Other templates in cloudflare/templates use the same setup with `defineWorkersConfig`.

### Does it deploy the Worker?

No. It runs `wrangler deploy --dry-run` through the existing `check` script to show the bundle builds, but a real deploy needs the account's credentials. The pull request is the hand-off; deploying to a preview or production is the reviewer's step after merging.

## More Cloudflare Workers jobs

- [Fix Cloudflare Worker Errors From Its Logs](https://getrush.ai/run/fix-cloudflare-worker-errors/cloudflare-workers/)
- [Turn Sentry Errors Into Fix Pull Requests for a Cloudflare Worker](https://getrush.ai/run/fix-sentry-errors/cloudflare-workers/)
- [Investigate Errors in a Cloudflare Worker](https://getrush.ai/run/investigate-worker-errors/cloudflare-workers/)

## The same job on other stacks

- [Add WebSockets to a Fastify App](https://getrush.ai/run/add-websockets/fastify/)
- [Add WebSockets to a Fiber App](https://getrush.ai/run/add-websockets/fiber/)
- [Add WebSockets to a Leptos App](https://getrush.ai/run/add-websockets/leptos/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
