# Add Cursor Pagination to a Hono API on Workers KV

Yes. An agent turns a load-everything KV list into a paged GET /posts with limit and cursor, keeps the response shape, adds vitest coverage, and opens a PR.

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

## What the agent does

The agent reads the data access before it changes a route. In an API shaped like the `blog` example of honojs/examples, `package.json` pins `hono` ^4.2.4, `wrangler` ^3.53.0, `vitest` 1.3.0 and `@cloudflare/vitest-pool-workers` ^0.2.0, with `npm run test` running `vitest --run`. `wrangler.example.toml` binds a KV namespace as `BLOG_EXAMPLE` with `nodejs_compat`. `src/index.ts` mounts `prettyJSON` and a `basicAuth` guard for non-`GET` methods on `/posts/*` under `/api`, and `src/api.ts` serves `GET` and `POST /posts` and `GET`, `PUT` and `DELETE /posts/:id`. The problem is in `src/model.ts`: `getPosts` calls `KV.list({ prefix: 'v1:post:' })`, then does one `KV.get` per key in a loop and returns every post. That is one list call plus one read per post on every request, and `KV.list` itself returns at most one page of keys, so a blog past that size silently loses posts.

It changes `getPosts` to take `{ limit, cursor }` and pass them through to `KV.list({ prefix: PREFIX, limit, cursor })`, which is where KV already does the paging: the result carries `keys`, `list_complete` and, when there is more, a `cursor` string. The function returns `{ posts, cursor }`, with `cursor` left out when `list_complete` is true, and still reads each key on the page with `KV.get`. In `src/api.ts`, `GET /posts` reads `limit` and `cursor` from `c.req.query()`, defaults `limit` to a page size the team picks and rejects a value that is not a positive integer or exceeds KV's list limit with a `400` in the same `{ error, ok: false }` shape the other errors use. The response keeps `posts` and `ok` exactly as before and adds `next_cursor`, so the existing client code that reads `posts` keeps working and a client that wants the next page passes `next_cursor` back as `cursor`. An invalid cursor makes `KV.list` throw; the agent catches that and answers `400` rather than `500`.

One thing the agent says plainly in the pull request rather than hiding: KV lists keys in lexicographic order, and this project's keys are `v1:post:` plus a random UUID, so pages come back in UUID order, not by date. A newest-first feed would need a different key scheme, such as an inverted timestamp before the id, which changes every existing key, so the agent does not do it unasked and describes the option instead.

Tests follow `src/api.test.ts`, which imports `env` from `cloudflare:test` and drives the app with `worker.request('/posts', {}, env)`. The suite runs with `isolatedStorage: false` in `vitest.config.ts`, so tests share one KV namespace and run in file order. The agent adds a `describe` block that creates three posts, requests `/posts?limit=2`, asserts two posts and a `next_cursor`, follows the cursor and asserts the remaining one with no `next_cursor`, then checks `limit=0`, `limit=abc` and a garbage cursor each return `400`, and deletes what it created in `afterAll` so the earlier tests that count posts still see the numbers they expect. `vitest.config.ts` points at `./wrangler.toml`, so the agent copies `wrangler.example.toml` to `wrangler.toml` locally as the README says, runs `npm run test`, and pastes the result in the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add cursor pagination to the posts list in this Hono API and open a pull request. Read package.json, wrangler.example.toml, src/index.ts, src/api.ts, src/model.ts, src/api.test.ts and vitest.config.ts first. Change getPosts in src/model.ts to accept limit and cursor and pass them to KV.list, returning the posts on that page and the cursor when list_complete is false. In src/api.ts make GET /posts read limit and cursor from the query, validate limit as a positive integer within KV's list limit, keep posts and ok in the response unchanged, add next_cursor, and answer 400 in the existing { error, ok: false } shape for a bad limit or a cursor that KV rejects. Do not change key names or ordering; state in the pull request that pages follow KV key order, which is UUID order here, and describe what a newest-first scheme would need. Add tests in src/api.test.ts that create three posts, page through them with limit=2, assert next_cursor behaviour, check the 400 cases, and clean up in afterAll so the existing tests still pass with isolatedStorage false. Copy wrangler.example.toml to wrangler.toml for the test run, run npm run test, and paste the output in the pull request. Do not change the auth middleware or the other routes.",
  "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 changes `src/model.ts`, `src/api.ts` and `src/api.test.ts`, with no new dependency. The description shows two example responses, one with `next_cursor` and the last page without it, the `400` body for a bad `limit`, the vitest summary, and a short note on key order and what a newest-first feed would need.

`GET /posts` without query parameters still returns `{ posts, ok }` with the first page, so a client that never heard of cursors keeps working and simply sees at most one page. `POST`, `PUT` and `DELETE` and the `basicAuth` middleware in `src/index.ts` are untouched.

A reviewer checks the default page size, that the upper bound on `limit` matches KV's list limit, that an invalid cursor is a `400` and not a `500`, and that the new tests leave the namespace as they found it. Then they decide whether UUID order is acceptable or whether to open a follow-up for a dated key scheme.

## Run it on every endpoint that lists a whole KV prefix

A team with several Workers that list a KV prefix into one response sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads that Worker's own model code, so a route that already takes `limit` gets only the cursor added, and each run opens its own pull request with its own tests.

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 the test output from.

## Why run it on Rush?

The easy version of this change is wrong in a quiet way: pass `limit` to `KV.list`, forget `list_complete`, and the last page always claims there is more. In a Rush sandbox the agent runs the real Workers test pool with a real KV binding, pages through posts it created, and keeps the output in the run's record, so the pull request shows the cursor stop at the right place.

The agent also reads the storage honestly: KV orders keys, not posts, and the pull request says so instead of implying a date-ordered feed. The same request works on any Hono route that lists a KV prefix.

## Frequently asked questions

### Does the response change for existing clients?

`posts` and `ok` stay as they are. The only addition is `next_cursor`, and a request with no query parameters returns the first page with the default `limit`, so a client that ignores the new field sees one page instead of everything.

### Why are pages not sorted by date?

KV returns keys in lexicographic order and the keys here are `v1:post:` followed by a UUID from `crypto.randomUUID()`. Sorting by date needs the date in the key, which means rewriting every existing key; the pull request describes that option and leaves the choice to you.

### What happens with a bad cursor?

`KV.list` throws on a cursor it did not issue. The route catches that and answers `400` with `{ error, ok: false }`, the same shape `POST /posts` uses for a bad body, and the test suite covers it.

### Does it still read one key at a time?

Yes, for the keys on one page, which is bounded by `limit`. Storing the post body in the key's metadata so `KV.list` returns it in one call is a further change the agent can make if asked; it is not needed for correct paging.

## More Hono jobs

- [Set Up GitHub Actions CI for a Hono Worker](https://getrush.ai/run/add-github-actions-ci/hono/)
- [Add Health Check Endpoints to a Hono API](https://getrush.ai/run/add-health-checks/hono/)
- [Add Input Validation to a Hono API](https://getrush.ai/run/add-input-validation/hono/)

## The same job on other stacks

- [Add Cursor Pagination to a Ktor API](https://getrush.ai/run/add-cursor-pagination/ktor/)
- [Add Cursor Pagination to a Litestar API](https://getrush.ai/run/add-cursor-pagination/litestar/)
- [Add Cursor Pagination to a Mongoose and Express API](https://getrush.ai/run/add-cursor-pagination/mongoose/)

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