# Add Cursor Pagination to a Cloudflare Worker on D1

Yes. An agent turns the fixed LIMIT 3 query in your D1-backed Worker into a keyset-paginated JSON route with a next cursor, a limit cap, tests, and a pull request.

[Run this on Rush](https://cloud.getrush.ai/run/add-cursor-pagination/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 query and the schema before it adds a parameter, because keyset pagination needs a column that is indexed and never changes. In a Worker shaped like `d1-template` in cloudflare/templates, `wrangler.json` sets `compatibility_date` to `2025-10-08`, binds a D1 database as `DB`, enables `observability` and uploads source maps; `package.json` has `wrangler 4.136.1` and `typescript 5.9.3` as its only dev dependencies, with `check` running `tsc && wrangler deploy --dry-run`, `seedLocalD1` running `wrangler d1 migrations apply DB --local` and `predeploy` applying them remotely. `migrations/0001_create_comments_table.sql` creates `comments` with `id INTEGER PRIMARY KEY NOT NULL`, `author` and `content`, and inserts three rows. `src/index.ts` runs `SELECT * FROM comments LIMIT 3` in `fetch` and hands the JSON to `renderHtml` in `src/renderHtml.ts`, which prints it inside a `<pre>` on a status page.

`id INTEGER PRIMARY KEY` in SQLite is the rowid, so it is the natural cursor. The agent adds `GET /api/comments` to `src/index.ts`, routed on `new URL(request.url).pathname`, which reads `limit` (default 20, at most 100, otherwise a `400` JSON error) and `after` (an integer id, or absent) and runs `SELECT id, author, content FROM comments WHERE id > ?1 ORDER BY id LIMIT ?2` through `env.DB.prepare(...).bind(after ?? 0, limit + 1).all()`. Fetching one extra row tells it whether a next page exists without a `COUNT(*)`. The response is `{ items, nextCursor }`, where `nextCursor` is the last returned id or is omitted on the final page, with `content-type: application/json`. The root path keeps serving the status page, but its query becomes the first page of the same function so the two can never disagree.

The template has no unit tests; the repository tests it end to end with `playwright-tests/d1-template.spec.ts`, which loads the page and expects the heading and the first comment's JSON to be visible. The agent adds `vitest` and `@cloudflare/vitest-pool-workers` as dev dependencies of the template only, a `vitest.config.ts` pointing at `wrangler.json`, and `src/index.test.ts` that applies the migration to the test D1 with `env.DB.exec`, inserts 25 rows, then walks `/api/comments?limit=10` following `nextCursor` and asserts strictly increasing ids, no repeated row, a missing cursor on the last page, and a `400` for `limit=0` and `limit=abc`. The Playwright assertion on the first comment still holds because the status page still shows the first three rows.

It runs `npm install`, `npm run check` for `tsc` and the dry-run deploy, `npm run seedLocalD1`, `npx vitest --run`, then `wrangler dev` and two `curl` calls, the second using the `nextCursor` from the first, and pastes both JSON responses and the test summary in the pull request. `wrangler.json` and the migration are unchanged, so nothing about the deployed database moves.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add cursor pagination to this D1-backed Cloudflare Worker and open a pull request. Read package.json, wrangler.json, tsconfig.json, worker-configuration.d.ts, migrations/0001_create_comments_table.sql, src/index.ts and src/renderHtml.ts first. Add GET /api/comments in src/index.ts, routed on the request pathname, taking limit (default 20, maximum 100, 400 with a JSON error otherwise) and after (an integer id). Run SELECT id, author, content FROM comments WHERE id > ?1 ORDER BY id LIMIT ?2 with limit plus one rows bound, and return { items, nextCursor } as JSON, omitting nextCursor on the last page. Make the root status page use the same function for its first page. Add vitest and @cloudflare/vitest-pool-workers as dev dependencies of this template, a vitest.config.ts pointing at wrangler.json, and src/index.test.ts that applies the migration SQL to the test database, inserts 25 rows, walks the pages asserting increasing ids, no repeats and no cursor on the last page, and checks the 400 cases. Run npm install, npm run check, npm run seedLocalD1 and npx vitest --run, start wrangler dev, curl two consecutive pages and paste the responses and test summary in the pull request. Do not change wrangler.json bindings or the migration.",
  "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 a route and a `listComments` function to `src/index.ts`, a `vitest.config.ts`, `src/index.test.ts`, and two dev dependencies plus a `test` script in `package.json`. The description shows two `curl` responses from `wrangler dev`, the first ending in a `nextCursor` and the second starting after it, and the vitest summary.

The repository's `check` script runs `tsc` and `wrangler deploy --dry-run`, and its Playwright suite loads the status page, so a type error or a broken first page fails on the pull request. The JSON route is new and has no end-to-end coverage, so the Workers vitest run and the pasted responses are the evidence for it.

A reviewer checks that the query binds `after` and `limit` as parameters rather than interpolating them, that `limit` is capped, that `nextCursor` is omitted and not `null` on the last page, and that the status page still renders the first three comments the Playwright test expects. Then they decide whether an index beyond the primary key is needed once `comments` grows a second sort order.

## Run it on every new list endpoint

A team with several Workers reading D1 tables sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own migration and binding, so a Worker whose table has a text primary key gets a `(created_at, id)` keyset instead of a bare id, and each opens its own pull request.

Send a `request_id` with each body so a retry returns the run already started. With a `webhook_url` on the API key, Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request from.

## Why run it on Rush?

Pagination is correct only at its edges, and the edges need rows. In a Rush sandbox the agent applies the template's own migration to a local D1, inserts enough rows to need three pages, and walks them through the Worker in the vitest Workers pool and through `wrangler dev`, with every command and response kept in the run's record. A reviewer sees the second page start exactly where the first ended.

The template has no tests of its own, so the agent brings the harness Cloudflare's other templates already use rather than leaving the route unverified. The same request body works unchanged on every D1 Worker a team runs, and several run at once in their own sandboxes.

## Frequently asked questions

### Why not LIMIT and OFFSET?

SQLite still reads and skips every offset row, so deep pages get slower, and a row inserted between two requests shifts the next page. `WHERE id > ? ORDER BY id LIMIT ?` walks the primary key index and stays stable, and `id INTEGER PRIMARY KEY` in the migration is that index.

### Does the status page change?

It still shows the first three comments and the same heading, so `playwright-tests/d1-template.spec.ts` passes unchanged. Behind it, the page now calls the same `listComments` function as the JSON route with a limit of 3, so the two views cannot drift apart.

### How does the test get a database?

`@cloudflare/vitest-pool-workers` reads the `d1_databases` binding from `wrangler.json` and gives each test an empty local D1 through `env` from `cloudflare:test`. The test applies the SQL from `migrations/0001_create_comments_table.sql` itself before inserting rows, so no remote database is touched.

### Will this run in the live deployment?

Yes. The query uses only `prepare`, `bind` and `all` from the D1 API already in use, and `wrangler.json` is unchanged. `npm run check` performs a dry-run deploy in the sandbox, so the bundle is known to build before the pull request is opened.

## More Cloudflare Workers jobs

- [Add D1 Migrations to a Cloudflare Worker](https://getrush.ai/run/add-d1-migrations/cloudflare-workers/)
- [Add a Durable Object to a Cloudflare Worker](https://getrush.ai/run/add-durable-objects/cloudflare-workers/)
- [Set Up GitHub Actions CI and Deploys for a Cloudflare Worker](https://getrush.ai/run/add-github-actions-ci/cloudflare-workers/)

## The same job on other stacks

- [Add Cursor Pagination to a Django REST Framework API from a Linear Issue](https://getrush.ai/run/add-cursor-pagination/django-rest-framework/)
- [Add Cursor Pagination to a Drizzle API](https://getrush.ai/run/add-cursor-pagination/drizzle/)
- [Add Cursor Pagination to an Echo API](https://getrush.ai/run/add-cursor-pagination/echo/)

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