# Add Input Validation to a Sequelize and Express API

Yes. An agent adds field allowlists and validators to your Sequelize models, maps ValidationError to 400 and UniqueConstraintError to 409, adds tests and opens a PR.

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

## What the agent does

The agent reads how a request body reaches the database before it adds a rule. In an API like the `express-main-example` in sequelize/express-example, `package.json` has `express ^4.17.1`, `body-parser ^1.19.0`, `sequelize ^6.3.3` and `sqlite3 ^5.0.0`, a `start` script, a `setup-example-db` script and no test script; `.npmrc` sets `package-lock=false`. `sequelize/index.js` opens `sqlite-example-database/example-db.sqlite` and defines three models from `sequelize/models/`: `user` with a `username` that is `unique` and validated by `is: /^\w{3,}$/`, `orchestra` with a `name`, and `instrument` with `type` and `purchaseDate`, where a commented-out `isIn` validator hints at what was never finished. `extra-setup.js` adds `orchestra.hasMany(instrument)` and `instrument.belongsTo(orchestra)`. `express/app.js` mounts each route module under `/api/<name>` through `makeHandlerAwareOfAsyncErrors`, which forwards a rejected promise to `next(error)` and nothing else: there is no error middleware, so Express's default handler answers.

That default handler is the problem the page fixes. `express/routes/users.js` does `models.user.create(req.body)` after only checking that `id` is absent, and `update` passes `req.body` straight to `models.user.update(req.body, { where: { id } })`, so a client can set any column, including `createdAt`. A username that fails the regex rejects with a `SequelizeValidationError`, a duplicate rejects with `SequelizeUniqueConstraintError`, and both come back as a 500 HTML page; `getIdParam` in `express/helpers.js` throws a `TypeError` for a non-numeric `:id`, which is also a 500. The agent adds an `errors.js` middleware registered after the routes in `app.js` that answers `ValidationError` with 400 and a JSON `errors` array of `path` and `message` from `error.errors`, `UniqueConstraintError` (which extends `ValidationError`, so it is matched first) with 409, `ForeignKeyConstraintError` with 400 for an instrument pointing at an orchestra that does not exist, where the dialect enforces the constraint, the helper's `TypeError` with 400, and everything else with 500 and no stack in the body.

Allowlists go where Sequelize already supports them. Each route module gets a `fields` constant, `['username']` for users, `['name']` for orchestras, `['type', 'purchaseDate', 'orchestraId']` for instruments, passed as `create(req.body, { fields })` and `update(req.body, { fields, where })`, so unknown keys are dropped rather than written. The models gain the validators the data implies: `orchestra.name` with `notEmpty`, `instrument.type` with the `isIn` list the comment left behind, `instrument.purchaseDate` with `isDate`. `update` also checks the affected-row count Sequelize returns and answers 404 when it is zero, where today it answers 200 for a row that does not exist. The response bodies of the happy paths do not change.

There are no tests, so the agent adds `supertest` as a dev dependency, a `test` script that runs `node --test test/`, and makes the storage path in `sequelize/index.js` overridable with a `DB_STORAGE` environment variable so each test file syncs a fresh SQLite file under `os.tmpdir()` and leaves the example database alone. `test/validation.test.js` covers a short username (400 with the `path` of `username`), a duplicate (409), an unknown column in a PUT body (200 and the column unchanged), a non-numeric `:id` (400), an instrument with a bad `orchestraId` (400) and an update of a missing id (404). The agent runs `npm install` and `npm test` in its sandbox and keeps the output.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add input validation and error handling to this Sequelize and Express API. Read package.json, .npmrc, index.js, express/app.js, express/helpers.js, every file under express/routes/ and sequelize/, and sqlite-example-database/setup.js first. Add an error middleware after the routes in express/app.js that answers UniqueConstraintError with 409, other ValidationError with 400 and a JSON errors array of path and message, ForeignKeyConstraintError with 400, the TypeError thrown by getIdParam with 400, and anything else with 500 and no stack. Add a fields allowlist per route module and pass it to create and update so unknown body keys are dropped; return 404 from update when no row matched. Add notEmpty to orchestra.name, the isIn list the comment in instrument.model.js describes to instrument.type, and isDate to instrument.purchaseDate. Make the SQLite storage path overridable with DB_STORAGE, add supertest as a dev dependency and a test script using node --test, and write test/validation.test.js covering a short username, a duplicate username, an unknown column in a PUT, a non-numeric id, an instrument with an unknown orchestraId and an update of a missing id, each against a fresh temporary database. Run npm install and npm test, include the output, update the readme's route list, and open a 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 that adds `express/errors.js` and `test/validation.test.js`, changes `express/app.js`, the three route modules, the three model files, `sequelize/index.js`, `package.json` and `readme.md`. `index.js`, the seed script and the response shapes of successful requests are unchanged.

The description lists each status code and which error class produces it, shows a 400 body for a bad username and a 409 for a duplicate, and quotes the `node --test` summary. The transcript at `GET /o/{org}/sessions/{id}/messages` keeps every command with its output.

Before merging, a reviewer decides whether the `isIn` list for instrument types should be a lookup table instead, whether 422 fits the team's conventions better than 400 for validation, and whether to commit a lockfile now that `.npmrc` turns it off and a test dependency has been added.

## Run it on every pull request that adds a route or a model

Run it from an automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "if this pull request adds a route under express/routes/ or a model under sequelize/models/, add the fields allowlist, the validators and the error cases for it on this branch, following express/errors.js". The trigger puts the pull request after the prompt, and the agent checks out that branch and pushes to it.

For the repositories you have today, send one `POST /o/{org}/sessions` per repository with this body and a `request_id` that is a UUID v5 of the repository's full name, so a retry returns the run already started. The key's `webhook_url` reports each finish with `session_url`.

## Why run it on Rush?

Validation in a Sequelize app is spread over three layers, model validators, the options passed to `create` and `update`, and the error middleware that turns a rejected promise into a status code, and a mistake in any one of them is invisible until a client sends something odd. The agent reads all three, changes them together and sends the odd requests itself against a real SQLite database in its own sandbox before anyone reviews a line.

The pull request carries the tests and the command output, so a reviewer sees each status code produced rather than reasoning about it, and several Express services on Sequelize can be done at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Why not validate with Joi or Zod in front of the routes?

The models already carry validators, `username` has one today, and Sequelize raises `ValidationError` with a `path` per field, so the fix is to let those run and translate the error. A schema library is a reasonable addition for shapes the database cannot express; name it in the prompt and the agent adds it as a middleware alongside the allowlists.

### Will existing clients see different responses?

Successful requests return the same bodies and codes. Only failures change: HTML 500 pages become JSON 400, 404 or 409 answers, and a PUT with extra keys now ignores them instead of writing them.

### Does this change the example database?

No. `npm run setup-example-db` still writes `sqlite-example-database/example-db.sqlite`. The tests set `DB_STORAGE` to a file under the OS temp directory and call `sequelize.sync({ force: true })` there.

### Why 409 for a duplicate username and not 400?

Because `UniqueConstraintError` is a conflict with existing state rather than a malformed body, and separating it lets a client retry with another name. Since the class extends `ValidationError`, the middleware matches it first; tell the agent if you want both as 400.

## More Sequelize jobs

- [Add Migrations to a Sequelize Express App](https://getrush.ai/run/add-migrations/sequelize/)
- [Add Optimistic Locking to a Sequelize App](https://getrush.ai/run/add-optimistic-locking/sequelize/)
- [Add Pagination to a Sequelize Express API](https://getrush.ai/run/add-pagination/sequelize/)

## The same job on other stacks

- [Add Request Validation to a Serverless API](https://getrush.ai/run/add-input-validation/serverless/)
- [Add Input Validation to a Slim 4 API](https://getrush.ai/run/add-input-validation/slim/)
- [Add Input Validation to a Socket.IO Chat](https://getrush.ai/run/add-input-validation/socket-io/)

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