# Add Cursor Pagination to a Sequelize + Express API

Yes. An agent turns each unbounded findAll in your Sequelize routes into a keyset-paginated list with a limit, an opaque cursor and a Link header, tested, in a PR.

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

## What the agent does

The agent starts from the list handlers, because that is where the unbounded queries are. In an API laid out like the `express-main-example` folder of sequelize/express-example, `express/app.js` mounts one router object per model from `express/routes/users.js`, `instruments.js` and `orchestras.js`, and wires each exported `getAll` to `GET /api/<route>` through `makeHandlerAwareOfAsyncErrors`. All three `getAll` functions call `findAll()` with no `order`, no `limit` and no `where`; `orchestras.js` adds `include: models.instrument` when `includeInstruments` is in the query string. The models in `sequelize/models/` all use an auto-incrementing integer `id` as primary key, `instrument` carries `type` and `purchaseDate`, and `extra-setup.js` gives `orchestra.hasMany(instrument)`. The database is SQLite at `sqlite-example-database/example-db.sqlite`, filled by `npm run setup-example-db` with four users, three orchestras and ten instruments each, and `package.json` pins `sequelize` 6, `express` 4 and `sqlite3` 5 with no test script and, per `.npmrc`, no lock file.

It writes one helper, `express/pagination.js`, rather than three copies: `parsePage(req)` reads `limit` (default 20, at most 100, anything else a 400 through the existing async-error wrapper) and `after`, an opaque base64url string that decodes to the last row's `id`; `pageQuery({ limit, after })` returns the Sequelize options `{ where: { id: { [Op.gt]: afterId } }, order: [["id", "ASC"]], limit: limit + 1 }`; and `sendPage(res, rows, limit, req)` drops the extra row, sets a `Link: <…?after=…>; rel="next"` header built from `req.originalUrl` when there was one, and sends the array. The body stays a plain array, so a client that reads `/api/users` today keeps working and only a client that follows `Link` pages. Each `getAll` becomes a merge of `pageQuery` with its own options, so orchestras keep their `include` and the cursor still applies to the parent rows, not the joined instruments.

Because `purchaseDate` is the order a reader expects for instruments, the agent documents in the pull request why the cursor is on `id` for every route: `id` is unique and indexed, while `purchaseDate` is random in the seed data and not unique, so a keyset on it needs a composite `(purchaseDate, id)` cursor and an index to match. It leaves that as a follow-up rather than guessing. `getIdParam` in `express/helpers.js` is reused for the decoded cursor so a tampered `after` answers 400 like a bad `:id`.

There is no test script, so the agent adds one on Node's built-in `node:test` runner with no new dependency: `tests/pagination.test.js` copies `setup.js`'s seeding into a temporary SQLite file, starts the app from `express/app.js` on an ephemeral port, and walks `/api/instruments?limit=12` until the `Link` header is absent, asserting that 30 distinct ids come back in ascending order, that `limit=500` is capped at 100, and that a garbage `after` is a 400. It raises `engines.node` in `package.json` from `>=10` to `>=18`, the first version with `node:test` and global `fetch`, and says so in the pull request since the README still names Node 10. It runs `npm install`, `npm run setup-example-db`, `npm test` and `npm start` in its sandbox and pastes the three requests of a full walk through the instruments list into 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 every list route in this Sequelize + Express API. Read package.json, .npmrc, index.js, express/app.js, express/helpers.js, express/routes/users.js, express/routes/instruments.js, express/routes/orchestras.js, sequelize/index.js, sequelize/models/*.js, sequelize/extra-setup.js and sqlite-example-database/setup.js first. Write one helper module, express/pagination.js, that parses limit (default 20, max 100, 400 on anything else) and after (an opaque base64url cursor holding the last id), builds the Sequelize options with where id greater than the cursor, order by id ascending and limit plus one, and sets a Link header with rel next when there is another page. Keep the response body a plain array so existing clients keep working. Apply it to the users, instruments and orchestras getAll handlers, keeping the includeInstruments option on orchestras. Explain in the pull request why the cursor is on id and what a purchaseDate cursor would need. Add a test script on node:test that seeds a temporary SQLite file, starts the app on an ephemeral port, walks the instruments list in pages of 12 and asserts 30 distinct ascending ids, the 100 cap and a 400 on a bad cursor; raise engines.node to 18 and say why. Run npm install, the seed script, the tests and the server in your sandbox and paste a full paged walk into the pull request. Change nothing in the create, update or delete handlers.",
  "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

The pull request adds `express/pagination.js` and `tests/pagination.test.js`, changes the three route files, and edits `package.json` for the `test` script and the `engines` line. Its description quotes the `node:test` summary, the `curl -i` output for three consecutive pages of `/api/instruments?limit=12` showing the `Link` header on the first two and none on the third, and the Sequelize log lines, which this project prints with parameters and timings because `sequelize/index.js` sets `logQueryParameters` and `benchmark`, so the reviewer can see the `WHERE id > ?` and `LIMIT 13` in the SQL that ran.

Nothing changes for a client that ignores the new query parameters except that `/api/users` now returns at most 20 rows ordered by `id`, which the description calls out as the one visible change and the reason for the default. The create, update and delete handlers and the models are untouched.

Before merging, a reviewer decides whether 20 is the right default for their clients, whether the `Link` header or a body envelope suits their front end, and whether to take the `purchaseDate` follow-up now. The `engines` change is the other decision: the test runner needs Node 18, and a deploy still on an older Node would need a different test setup.

## Run it on every list route without a limit

An engineer who found the unbounded `findAll` while debugging a slow page starts this from the terminal with this body and goes back to the bug. The run reads the real routes and models, so the helper it writes matches the primary keys, associations and query options this API has rather than a template written for another ORM.

Send a `request_id`, a UUID, with the body so a retried start returns the run it already began. The pull request link is on the run's `GET /o/{org}/sessions/{id}` answer once it is open, and a key with a `webhook_url` hears `run.completed` when the turn ends. A service with several Sequelize APIs sends one body per repository, each with its own `resources` URL.

## Why run it on Rush?

Keyset pagination is easy to describe and easy to get subtly wrong: an off-by-one on `limit + 1`, a cursor on a non-unique column that skips rows, a `Link` header built from the wrong URL behind a proxy. The agent proves each of those against the real app in its own sandbox, seeding the SQLite database the project already ships a script for, starting the server and walking the pages with `curl`, and the pull request carries that walk rather than a promise.

The transcript keeps every command and its output, so the reviewer reads the SQL Sequelize ran, the headers each page returned and the test runner's summary without checking the branch out. Several services can be paginated at once, each in its own sandbox with its own database file, and nothing merges until a person reads the diff.

## Frequently asked questions

### Why keep the body a plain array instead of adding a next_cursor field?

The three list routes answer a bare JSON array today, and a client that expects one would break on an envelope. The `Link` header with `rel="next"` carries the cursor without changing the body, so old clients keep working and new ones follow the header. If every client is yours, an envelope is a one-line change in `sendPage`, and the pull request says where.

### Why is the cursor on id and not on purchaseDate for instruments?

A keyset cursor must be on a unique, indexed ordering, or rows with equal values at a page boundary are skipped or repeated. `id` is the auto-incrementing primary key in every model here. `purchaseDate` is neither unique nor indexed, and the seed script fills it with random dates, so a date ordering needs a composite `(purchaseDate, id)` cursor and an index, which the pull request describes as the next step.

### Does it work with the includeInstruments option on orchestras?

Yes. The pagination options are merged into the orchestras query, so `where`, `order` and `limit` apply to the orchestra rows, and `include: models.instrument` still attaches each orchestra's instruments. Sequelize applies `limit` to the parent model when a `hasMany` include is present, so a page of 20 orchestras can carry 200 instruments; the pull request notes that `separate: true` on the include is the fix if that becomes heavy.

### Why does it change the Node version?

The project has no test runner and, per `.npmrc`, no lock file, so adding Jest or Mocha would add unpinned dependencies. Node's built-in `node:test` and global `fetch` need Node 18, which is why `engines.node` moves from `>=10`. The runtime code itself still runs on older Node; only the tests need 18, and the pull request says so.

### Will it touch the create, update and delete handlers?

No. The prompt limits the change to the `getAll` handlers and the new helper, and the diff shows exactly that. The `getIdParam` helper is reused for the decoded cursor, so a tampered `after` answers 400 through the same `TypeError` path a bad `:id` already takes.

## More Sequelize jobs

- [Add Database Indexes to a Sequelize App](https://getrush.ai/run/add-database-indexes/sequelize/)
- [Move a Sequelize App From sync() to Migrations](https://getrush.ai/run/add-database-migrations/sequelize/)
- [Add Dependabot to a Sequelize App](https://getrush.ai/run/add-dependabot/sequelize/)

## The same job on other stacks

- [Add Cursor Pagination to a Serverless DynamoDB API](https://getrush.ai/run/add-cursor-pagination/serverless/)
- [Add Cursor Pagination to a Slim 4 API](https://getrush.ai/run/add-cursor-pagination/slim/)
- [Add Cursor Pagination to a SQLAlchemy API](https://getrush.ai/run/add-cursor-pagination/sqlalchemy/)

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