# Add a Durable Object to a Cloudflare Worker

Yes. An agent moves per-list state from KV into a SQLite-backed Durable Object class, declares its binding and migration in wrangler config, tests it and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-durable-objects/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 how the Worker keeps state today and where that falls short. In the `to-do-list-kv-template` in cloudflare/templates, a Remix 2.17.2 app runs on Workers with static assets: `wrangler.jsonc` sets `compatibility_date` 2025-10-08, the `nodejs_compat` flag, `main` as `./server.ts` and one KV namespace bound as `TO_DO_LIST`. `app/to-do-manager.ts` is the whole data layer: `TodoManager` stores each list as one JSON array under a key, the route `app/routes/$id.tsx` passes `params.id` as that key, and `create`, `toggle` and `delete` each do `list()` then `kv.put` with `expirationTtl: 300`. Two things follow from that code. Every write is a read-modify-write on an eventually consistent store, so two people adding items to the same list at once can lose one, and every list disappears five minutes after its last write. `app/routes/_index.tsx` redirects to a fresh `nanoid()`, `server.ts` builds the Remix request handler and passes `env` through `load-context.ts`, and `test/to-do-manager.test.ts` runs under `@cloudflare/vitest-pool-workers` 0.11.1 with `env.TO_DO_LIST` from `cloudflare:test`, `singleWorker: true` and the wrangler config path, covering list, create, toggle and delete. The `check` script runs `tsc`, the Remix build and `wrangler deploy --dry-run` on wrangler 4.136.1. Next door in the same repository, `hello-world-do-template` shows the shape to copy: a class extending `DurableObject<Env>` from `cloudflare:workers`, a `migrations` entry with `new_sqlite_classes`, `ctx.storage.sql.exec`, and `idFromName` on the namespace binding.

The agent writes `app/todo-list.ts` exporting `class TodoList extends DurableObject<Env>`. Its constructor creates the table once with `ctx.storage.sql.exec` inside `ctx.blockConcurrencyWhile`: `todos(id TEXT PRIMARY KEY, text TEXT NOT NULL, completed INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL)`. Four RPC methods, `list`, `create`, `toggle` and `delete`, carry over the `TodoManager` contract, with `list` ordering by `created_at` descending as before, and `toggle` throwing the same not-found error. Because wrangler loads Durable Object classes from the module named in `main`, `server.ts` re-exports `TodoList`. `wrangler.jsonc` gains `durable_objects.bindings` with `name: 'TODO_LIST'` and `class_name: 'TodoList'`, and a `migrations` entry tagged `v1` with `new_sqlite_classes: ['TodoList']`; `wrangler types` regenerates `worker-configuration.d.ts` so `Env` has `TODO_LIST: DurableObjectNamespace<TodoList>`. The route then does `env.TODO_LIST.get(env.TODO_LIST.idFromName(params.id))` and calls the stub's methods directly, which is the whole point: one object per list, every request for that list serialised through it, no expiry.

Existing lists are not thrown away. On its first `list()` call an object checks whether its table is empty and, if the old KV binding is still configured, reads the JSON array under its own name, inserts the rows and leaves the KV key to expire on its own. The pull request keeps the KV binding for one deploy for exactly this reason and says when it can be removed. `TodoManager` and its test are deleted once the new test covers the same cases, so the data layer does not exist twice.

The new test, `test/todo-list.test.ts`, runs in the same Workers pool and uses `runInDurableObject` from `cloudflare:test` to call the methods on a real instance: an empty list, create then list in order, toggle, delete, and two lists with different names that do not see each other. A sixth case fires two creates at the same object without awaiting between them and asserts both rows exist, which is the failure the KV version had. `pnpm check` then runs `tsc`, the Remix build and the dry-run deploy, which validates the binding and migration before anything ships; `pnpm lint` runs ESLint as before.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Move this Worker's per-list to-do state from KV into a Durable Object. Read wrangler.jsonc, server.ts, load-context.ts, app/to-do-manager.ts, the routes, the Vitest config and the existing tests first, and read the hello-world-do-template in the same repository for the class, migration and binding shape. Write a SQLite-backed Durable Object class with list, create, toggle and delete methods that keep the current ordering and error behaviour, create its table in the constructor inside blockConcurrencyWhile, re-export the class from the Worker entry, add the binding and a v1 migration with new_sqlite_classes to wrangler.jsonc, regenerate the types, and change the list route to call the stub for the list id. Import an existing list from KV the first time its object is used and keep the KV binding for one deploy. Replace the old test with a vitest-pool-workers test using runInDurableObject that covers the four operations, isolation between two lists and two concurrent creates. Run the check script and lint and open a pull request that explains the migration tag and when the KV binding can go.",
  "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 that adds `app/todo-list.ts` and `test/todo-list.test.ts`, edits `wrangler.jsonc`, `server.ts`, `app/routes/$id.tsx` and `worker-configuration.d.ts`, and removes `app/to-do-manager.ts` with its test. Its description explains the `v1` migration tag and why it must never be renamed, shows the six test cases, and names the deploy after which the `kv_namespaces` entry can be deleted.

The run's record keeps the Vitest output from the Workers pool, the `tsc` and Remix build output, and the `wrangler deploy --dry-run` result that accepted the new binding and migration.

Before merging, a reviewer reads the constructor and the import path, because those run once per object and are the hardest to change later, runs `npm run preview`, which builds and serves through `wrangler dev`, to add items to one list from two tabs, and after deploying checks the Durable Objects page in the Cloudflare dashboard for the `TodoList` class with the `v1` migration applied.

## Run it on every Linear issue labelled workers

A team that plans platform work in Linear adds an automation with a `linear` trigger on `linear.issue.labeled` for the label `workers`, the Project that holds this repository, and this prompt. Labelling the issue that describes the lost-write bug starts one run; the issue's text lands after the prompt, so the reporter's steps to reproduce reach the agent as written.

The trigger changes nothing in the prompt itself, so the next issue on the same automation, a WebSocket broadcast from the same object or an alarm that clears old lists, only needs to say what it wants.

## Why run it on Rush?

The move from KV to a Durable Object is a small amount of code wrapped in three configuration details, the class export, the binding and the migration tag, and a mistake in any of them shows up only at deploy time. The agent runs the dry-run deploy that validates all three, runs the tests inside the Workers runtime rather than a Node imitation of it, and keeps the output, so the reviewer sees the configuration accepted before it reaches an account.

It also writes the test the old code could not pass, two concurrent writes to one list, and that test stays in the repository as the reason the change was made.

## Frequently asked questions

### Why SQLite-backed rather than the key-value storage API?

New Durable Object classes are declared with `new_sqlite_classes`, which is what the Durable Objects starter in the same repository uses, and a `todos` table with a primary key maps directly onto the four operations. The key-value API still exists, but a table makes ordering by creation time one `ORDER BY` instead of a sort in JavaScript.

### What happens to lists people already have?

The first time a list's object is used it checks for an empty table, reads the JSON array under the same name from the KV binding if one is still configured, and inserts the rows. Keys in KV were written with a five-minute expiry, so only recently used lists exist to import, and the pull request says when the KV binding can be removed.

### Can I rename the migration tag later?

No. Cloudflare applies migrations by tag in order and remembers which have run, so `v1` with `new_sqlite_classes: ['TodoList']` is permanent once deployed. Renaming the class later is its own migration with `renamed_classes`, which the pull request description notes for the future.

### Does wrangler dev run Durable Objects locally?

Yes. `npm run preview` builds the app and serves it with `wrangler dev`, which runs the Worker, the object and its SQLite storage in the local runtime, and the test pool runs that same runtime, which is why the tests call real instances through `runInDurableObject` rather than mocks. The `dev` script goes through Remix's Vite dev proxy instead, and the pull request says to use `preview` when checking the object.

## More Cloudflare Workers jobs

- [Set Up GitHub Actions CI and Deploys for a Cloudflare Worker](https://getrush.ai/run/add-github-actions-ci/cloudflare-workers/)
- [Add a Health Check Endpoint to a Cloudflare Worker](https://getrush.ai/run/add-health-checks/cloudflare-workers/)
- [Validate Request Bodies in a Cloudflare Worker](https://getrush.ai/run/add-input-validation/cloudflare-workers/)

## More jobs like this: Turn a Linear label into a PR

- [Enable DynamoDB Point-in-Time Recovery in an AWS CDK Stack from a Linear Issue](https://getrush.ai/run/add-dynamodb-point-in-time-recovery/aws-cdk/)
- [Add Email Verification to a Filament Panel from a Linear Issue](https://getrush.ai/run/add-email-verification/filament/)
- [Add Error Boundaries to a React App](https://getrush.ai/run/add-error-boundaries/react/)

## 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/)
