# Migrate a Hono Worker from KV to D1

Yes. An agent moves your Hono blog API from Workers KV to a D1 table with a migration, keeps the routes' JSON, imports existing posts, tests it, and opens a PR.

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

## What the agent does

The agent reads how posts are stored before it changes the binding. In a Worker shaped like the `blog` workspace of honojs/examples, `src/model.ts` keeps each post as a JSON string under a KV key prefixed `v1:post:` followed by a `crypto.randomUUID()`. `getPosts` does a `KV.list({ prefix })` and then one `KV.get` per key in a loop, so listing costs one read per post on every request, and the result has no order because KV lists keys lexically by UUID. `updatePost` reads the post, overwrites `title` and `body`, and writes it back, so two updates at the same moment lose one. `src/api.ts` mounts the five routes, `GET` and `POST /posts`, `GET`, `PUT` and `DELETE /posts/:id`, answers `{ posts, ok }` and `{ post, ok }`, `422` when a create has no title or body, `404` on a missing post, and `204` with no body when a `PUT` or `DELETE` targets one.

`src/bindings.ts` types the env as `USERNAME`, `PASSWORD` and `BLOG_EXAMPLE: KVNamespace`; `src/index.ts` wraps non-`GET` requests under `/posts/*` in `basicAuth` with those two values and `export default app`. `wrangler.example.toml` names the Worker `hono-example-blog`, sets `compatibility_date` 2024-04-01 and `nodejs_compat`, and binds the one KV namespace. `package.json` has `hono` ^4.2.4, `wrangler` ^3.53.0, `vitest` pinned to 1.3.0 and `@cloudflare/vitest-pool-workers` ^0.2.0; `vitest.config.ts` runs the suite inside workerd through `defineWorkersConfig` with `isolatedStorage: false` and `wrangler: { configPath: './wrangler.toml' }`, and `src/api.test.ts` imports `env` from `cloudflare:test`, expects an empty list first, then creates, reads, updates and deletes one post through `worker.request`.

The agent adds `migrations/0001_posts.sql` with a `posts` table of `id text primary key`, `title text not null`, `body text not null` and `created_at text not null default (datetime('now'))`, and a `[[d1_databases]]` block in `wrangler.example.toml` binding `BLOG_DB` with `migrations_dir = "migrations"`. `src/model.ts` keeps every exported name and return type and swaps the body: `getPosts` becomes one `prepare('select id, title, body from posts order by created_at desc').all<Post>()`, `getPost` a `bind(id).first<Post>()`, `createPost` an insert with the same `randomUUID`, `updatePost` a single `update ... where id = ?` whose `meta.changes` says whether a row existed, and `deletePost` the same with `delete`. `src/bindings.ts` gains `BLOG_DB: D1Database` and keeps `BLOG_EXAMPLE` until the import is done. `src/api.ts` changes only the binding it passes, so every status code and JSON shape stays as the tests expect.

For the data already in KV, the agent writes `scripts/kv-to-d1.mjs`, which runs `wrangler kv:key list` with the `v1:post:` prefix, fetches each value, and writes `migrations/0002_import_posts.sql` of `insert or ignore` rows, so the import is itself a migration applied with `wrangler d1 migrations apply`. The tests get a database the pool's documented way: `vitest.config.ts` reads the migrations with `readD1Migrations` and passes them as a `TEST_MIGRATIONS` binding, and a `test/apply-migrations.ts` setup file calls `applyD1Migrations(env.BLOG_DB, env.TEST_MIGRATIONS)` before the suite. The existing `api.test.ts` runs unchanged against D1, plus a new case that creates two posts and asserts the newest comes first. The agent runs `npm test`, `npx tsc --noEmit` and `wrangler d1 migrations apply hono-example-blog --local` followed by `wrangler dev` and a `curl` against `/api/posts`, and keeps the output.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Migrate this Hono Worker's post storage from Workers KV to D1 and open a pull request. Read package.json, wrangler.example.toml, vitest.config.ts, tsconfig.json, src/index.ts, src/api.ts, src/model.ts, src/bindings.ts and src/api.test.ts first. Add migrations/0001_posts.sql with a posts table of id, title, body and created_at, and a d1_databases binding named BLOG_DB with migrations_dir set in wrangler.example.toml. Rewrite src/model.ts so getPosts, getPost, createPost, updatePost and deletePost keep their names and return types but use prepared D1 statements, with getPosts ordered newest first and updatePost and deletePost reporting through meta.changes. Change src/api.ts only where it passes the binding; keep every status code and JSON shape. Write scripts/kv-to-d1.mjs that lists the v1:post: keys with wrangler, reads each value and writes migrations/0002_import_posts.sql with insert or ignore rows. Make the tests apply the migrations through readD1Migrations in vitest.config.ts and applyD1Migrations in a setup file, keep src/api.test.ts passing, and add a case for ordering. Run npm test, npx tsc --noEmit, wrangler d1 migrations apply --local and a wrangler dev smoke check, and paste the output in the 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 with two files under `migrations/`, a `scripts/kv-to-d1.mjs`, a rewritten `src/model.ts`, a one-field change in `src/bindings.ts`, a one-word change per route in `src/api.ts`, a `[[d1_databases]]` block in `wrangler.example.toml`, and a `vitest.config.ts` plus setup file that apply the migrations before tests. The description pastes the Vitest summary, the `tsc --noEmit` result, the local migration output and the `curl` against `wrangler dev`, and lists the three commands to run once against production: create the database, apply the migrations, deploy.

The example repository has no test workflow, so the pasted Vitest run is the check; on a repository with a Vitest workflow the suite runs on the pull request against the migrated model.

A reviewer checks that the five routes answer exactly as before through the unchanged tests, that `0002_import_posts.sql` holds their real posts with the same ids, that `created_at` has a default so old rows import without one, and that the KV binding is still declared so a rollback is one deploy. They merge, run the import migration against production, then remove `BLOG_EXAMPLE` in a later pull request.

## Run it on every Worker that has outgrown KV

A team with several Workers that keep JSON in KV sends one `POST /o/{org}/sessions` per repository, with this prompt and the repository in `resources`. Each run reads that Worker's own key layout and model functions, so a Worker that stores one blob per user gets a table shaped for that, and each run opens its own pull request.

Send a `request_id` with each call so a retry returns the run already started, and give the key a `webhook_url` so `run.completed` arrives with `session_url` when the turn ends and your handler can post the pull request where the platform team reads it.

## Why run it on Rush?

A storage migration is the kind of change nobody wants to make from a laptop with a production binding in `wrangler.toml`: one wrong `wrangler d1 execute` and the data is gone. In a Rush sandbox the agent works against a local D1 through `wrangler dev` and the Vitest pool, writes the import as a migration a person applies on purpose, and keeps every command and its output in the run's record beside the pull request.

Rewriting five model functions is quick; proving the routes still answer `201`, `204`, `404` and `422` in the same places, and that the tests get a migrated database inside workerd, is the slow part. The agent does both in one pass, and a follow-up such as "add a `GET /posts?limit=` with a cursor" wakes the same parked sandbox and lands on the same branch.

## Frequently asked questions

### Is existing KV data moved to D1?

The pull request includes `scripts/kv-to-d1.mjs`, which exports the `v1:post:` keys into `migrations/0002_import_posts.sql`, and the agent runs it against the local KV in the sandbox to show the output shape. A person runs it against production once, reviews the generated rows, and applies them with `wrangler d1 migrations apply`, so no production data is read or written by the run itself.

### How do the tests get a database?

`@cloudflare/vitest-pool-workers` runs the suite inside workerd with the bindings from `wrangler.toml`, so `env.BLOG_DB` is a real local D1. `vitest.config.ts` reads the `migrations/` directory with `readD1Migrations` and hands it to the tests as a binding; a setup file applies it with `applyD1Migrations` before the first test, so `GET /posts` still sees an empty table first.

### Why keep the KV binding?

So a rollback is a redeploy of the previous commit with no configuration change, and so the import script can read the old keys. `src/bindings.ts` keeps `BLOG_EXAMPLE` typed, nothing reads it after the change, and the pull request description says to remove it once the import has been applied.

### What changes for the API's callers?

Nothing in the status codes or JSON. The one visible difference is order: `GET /posts` returns newest first because the table has `created_at`, where KV returned keys in UUID order. The new test pins that order so it does not drift.

## More Hono jobs

- [Review Pull Requests on a Hono API](https://getrush.ai/run/review-pull-requests/hono/)
- [Upgrade npm Dependencies in a Hono API](https://getrush.ai/run/upgrade-npm-dependencies/hono/)
- [Write API Integration Tests for a Hono App](https://getrush.ai/run/write-api-tests/hono/)

## The same job on other stacks

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

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