# Migrate a Cloudflare Worker from KV to D1

Yes. An agent replaces a Worker KV JSON blob with a D1 table and migration, keeps the data access interface, runs the vitest pool against D1, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/migrate-kv-to-d1/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 stores data before it changes the binding. In an app shaped like the `to-do-list-kv-template` of cloudflare/templates, `wrangler.jsonc` sets `main` to `./server.ts`, serves `./build/client` as assets, enables `nodejs_compat` and observability, and binds one KV namespace as `TO_DO_LIST`. `app/to-do-manager.ts` is the only file that touches it: `TodoManager(kv, todosKey)` stores the whole list for one URL id as a single JSON value, reads and rewrites it on every `create`, `toggle` and `delete`, sorts by `createdAt` in `list()`, and puts every value with `expirationTtl: 300`, so a list disappears five minutes after its last write. `app/routes/$id.tsx` passes `context.cloudflare.env.TO_DO_LIST` and `params.id` to it from a Remix 2.17.2 loader and action. `test/to-do-manager.test.ts` drives the class through `env.TO_DO_LIST` from `cloudflare:test`, and `vitest.config.ts` uses `defineWorkersConfig` with `singleWorker: true` and `wrangler: { configPath: "./wrangler.jsonc" }`. `package.json` runs `tsc && remix vite:build && wrangler deploy --dry-run` as `check`, on `wrangler` 4.136.1 and `@cloudflare/vitest-pool-workers` 0.11.1.

The same repository's `d1-template` shows the shape D1 takes here, and the agent reads it instead of guessing: a `d1_databases` block in `wrangler.json` with `binding`, `database_name` and `database_id`, a `migrations/0001_create_comments_table.sql` file with the `-- Migration number:` header `wrangler d1 migrations create` writes, and `package.json` scripts `seedLocalD1` running `wrangler d1 migrations apply DB --local` and `predeploy` running the same with `--remote`. Following that, the agent writes `migrations/0001_create_todos.sql` with a `todos` table of `id TEXT PRIMARY KEY`, `list_id TEXT NOT NULL`, `text TEXT NOT NULL`, `completed INTEGER NOT NULL DEFAULT 0` and `created_at INTEGER NOT NULL`, plus an index on `(list_id, created_at)`, and replaces `kv_namespaces` in `wrangler.jsonc` with a `d1_databases` entry bound as `DB`, with a placeholder `database_id` the README tells you to replace after `wrangler d1 create`.

`TodoManager` keeps its constructor shape and its four methods so `$id.tsx` changes only the binding it passes: `list()` becomes `SELECT ... WHERE list_id = ? ORDER BY created_at DESC`, `create()` an `INSERT`, `toggle()` an `UPDATE ... SET completed = NOT completed WHERE id = ? AND list_id = ? RETURNING *` that throws the same `not found` error when no row comes back, and `delete()` a `DELETE`. SQLite has no boolean, so the class maps `completed` between `0`/`1` and `boolean` at the edge and the `Todo` type is unchanged for the route. The read-modify-write races and the five-minute expiry of the KV version are gone; the agent says so in the pull request and offers a scheduled cleanup as a follow-up rather than silently keeping an expiry.

For tests, the agent uses the D1 support in `@cloudflare/vitest-pool-workers`: `vitest.config.ts` reads the migrations directory with `readD1Migrations` and passes them as a `TEST_MIGRATIONS` binding through `miniflare.bindings`, a `test/apply-migrations.ts` setup file calls `applyD1Migrations(env.DB, env.TEST_MIGRATIONS)`, and `test/env.ts` declares both bindings on `ProvidedEnv`. The existing cases in `to-do-manager.test.ts` keep their assertions and switch `afterEach` from deleting one KV key to `DELETE FROM todos`. The agent runs `pnpm wrangler types` so `worker-configuration.d.ts` shows `DB: D1Database`, updates the README setup steps to `wrangler d1 create` and `wrangler d1 migrations apply`, then runs `pnpm check` and `pnpm test` and pastes both results into the pull request.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Migrate this Cloudflare Worker from KV to D1 and open a pull request. Read wrangler.jsonc, package.json, server.ts, load-context.ts, app/to-do-manager.ts, app/routes/$id.tsx, test/to-do-manager.test.ts, test/env.ts, vitest.config.ts and README.md first, and read the d1-template directory of cloudflare/templates for the wrangler config, migration file format and scripts it uses. Add migrations/0001_create_todos.sql with a todos table keyed by id, with list_id, text, completed as an integer and created_at, and an index on list_id and created_at. Replace the kv_namespaces binding in wrangler.jsonc with a d1_databases entry bound as DB and a placeholder database_id. Rewrite TodoManager to take a D1Database and a list id, keeping the constructor shape, the four methods, their return types and the not-found error on toggle, mapping completed between integer and boolean. Pass env.DB from $id.tsx. Add seedLocalD1 and predeploy scripts like d1-template. Wire tests with readD1Migrations in vitest.config.ts, a TEST_MIGRATIONS binding, a setup file that calls applyD1Migrations, and ProvidedEnv types in test/env.ts; keep every existing test case and clear the table in afterEach. Run wrangler types, update the README setup steps, run pnpm check and pnpm test, and paste both outputs in the pull request. State in the description that the five-minute expiry and the read-modify-write pattern are gone. Do not change the UI in $id.tsx beyond the binding.",
  "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 `migrations/0001_create_todos.sql` and `test/apply-migrations.ts`, rewrites `app/to-do-manager.ts`, and edits `wrangler.jsonc`, `app/routes/$id.tsx`, `vitest.config.ts`, `test/env.ts`, `test/to-do-manager.test.ts`, `worker-configuration.d.ts`, `package.json` and `README.md`. The description shows the `pnpm check` output, including the `wrangler deploy --dry-run` line, the vitest summary with every original case passing against D1, and a note on the two behaviours that changed.

`pnpm check` runs `tsc`, the Remix build and a dry-run deploy, so a type the new binding breaks or a config the dry run rejects fails before review. The route file changes only the binding it passes, so the page and its forms look and behave as before, except that lists no longer vanish after five idle minutes.

A reviewer checks the table and index, that `toggle` still throws for a missing id, the integer-to-boolean mapping, that `afterEach` clears the table so cases stay independent under `singleWorker`, and that the README's `wrangler d1 create` step is clear. Then they create the database, paste its id into `wrangler.jsonc` and run `predeploy`.

## Run it on every Worker outgrowing a KV blob

A team with several small Workers that keep a list in one KV value sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads that Worker's own data access code and tests, designs a table for its shape, and opens its own pull request with the migration and the test wiring for that project.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request and both check outputs from.

## Why run it on Rush?

Moving storage is the kind of change that looks done when the types compile and is actually done when the tests run against the new store. In a Rush sandbox the agent applies the migration to a local D1 through the Workers vitest pool, runs the original test cases against it, and keeps the output in the run's record, so the pull request shows the same assertions passing on the new backend.

The agent also reads the behaviours the old store had by accident, the five-minute expiry and the rewrite-the-whole-list pattern, and names them in the pull request instead of carrying them over or dropping them unmentioned. The same request works on any Worker whose data access sits behind one class.

## Frequently asked questions

### Is existing KV data moved to D1?

No. Every value in this template expires five minutes after its last write, so there is nothing durable to move. If your Worker keeps long-lived KV data, ask for a one-off migration script in the prompt and the agent writes one that lists the prefix and inserts rows.

### Why does the todo list stop expiring?

The KV version set `expirationTtl: 300` on every write, so a list vanished after five idle minutes. A D1 row has no expiry. The pull request keeps rows forever and describes a scheduled cleanup as the way to add retention on purpose.

### How do the tests get a database?

`@cloudflare/vitest-pool-workers` provides a local D1 for the `DB` binding in `wrangler.jsonc`. `vitest.config.ts` reads the `migrations` directory with `readD1Migrations` and a setup file applies them with `applyD1Migrations` before the suite runs, so the schema in tests is the one `wrangler d1 migrations apply` uses.

### What do I do after merging?

Run `wrangler d1 create` with the name in `wrangler.jsonc`, paste the returned id into `database_id`, and deploy; the `predeploy` script applies the migration to the remote database first, as `d1-template` does.

## More Cloudflare Workers jobs

- [Review Pull Requests on a Cloudflare Workers Project](https://getrush.ai/run/review-pull-requests/cloudflare-workers/)
- [Write Tests for a Cloudflare Worker With Durable Objects](https://getrush.ai/run/write-unit-tests/cloudflare-workers/)
- [Write Vitest Tests for a Cloudflare Worker](https://getrush.ai/run/write-workers-vitest-tests/cloudflare-workers/)

## The same job on other stacks

- [Migrate a Hono Worker from KV to D1](https://getrush.ai/run/migrate-kv-to-d1/hono/)

## More jobs like this: Hand off a long task

- [Move a Laravel App from Laravel Mix to Vite](https://getrush.ai/run/migrate-laravel-mix-to-vite/laravel/)
- [Migrate Mocha Tests to the Built-In Node.js Test Runner](https://getrush.ai/run/migrate-mocha-to-node-test/mocha/)

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