# Add Input Validation to a Node.js Express App

Yes. An agent adds validation chains to every Express route that reads input, removes eval parsing, re-renders forms with field errors, and opens a PR.

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

## What the agent does

The agent clones the repository into its own cloud sandbox and reads every handler that touches a request before it picks a library. In an app like OWASP/NodeGoat, `server.js` builds an Express 4 app with `body-parser`, `express-session`, Swig templates through `consolidate` and a MongoDB connection, with `csurf` and `helmet` present in `package.json` but commented out. `app/routes/index.js` maps `/login`, `/signup`, `/profile`, `/contributions`, `/benefits`, `/allocations/:userId`, `/memos`, `/learn` and `/research` to handler objects under `app/routes/`, each constructed with the database and backed by a DAO under `app/data/`.

Each handler parses input its own way. `contributions.js` runs `eval(req.body.preTax)`, `eval(req.body.afterTax)` and `eval(req.body.roth)` with the `parseInt` fix in a comment below, then checks for `NaN`, negatives and a 30 percent total. `profile.js` tests `bankRouting` with `/([0-9]+)+\#/`, a nested quantifier that backtracks catastrophically, and passes `firstName`, `lastName`, `ssn`, `dob`, `address` and `bankAcc` through unchecked. `allocations.js` takes `userId` from `req.params` and `threshold` from `req.query` straight into `getByUserIdAndThreshold`. `memos.js` inserts `req.body.memo` as it arrives. `session.js` validates signup with a hand-written `validateSignup`. The `/learn` route redirects to `req.query.url` unchecked. `package.json` runs tests through `grunt test`, whose `mochaTest:unit` target reads `test/unit/*.js`, a directory that does not exist; `test/security/profile-test.js` drives Selenium and ZAP, and `test/e2e/integration` holds Cypress specs per page. The `Dockerfile` runs on `node:12-alpine`.

The agent chooses `express-validator`, whose 6.x line still runs on the Node 12 the Dockerfile pins, and writes the chains in `app/routes/validators.js`, one export per route: `body('preTax').isInt({ min: 0, max: 30 }).toInt()` and the same for the other two, with a custom check that the three sum to at most 30; `bankRouting` matched by `/^[0-9]+#$/` with no nested quantifier; `ssn`, `dob`, `bankAcc` and `website` given the formats the profile view expects; `param('userId').isInt().toInt()` and `query('threshold').optional().isInt({ min: 0, max: 99 }).toInt()` for allocations; a trimmed, length-limited `memo`; the signup fields that `validateSignup` covered; and `query('url')` on `/learn` restricted to a same-origin path, which closes the open redirect at the same time. Each handler calls `validationResult(req)` and, when errors exist, re-renders its Swig view with `updateError` and the field list, the shape `contributions.html` and `profile.html` already display. The `eval` calls go, and the `parseInt` comment with them.

The agent creates `test/unit/` so `grunt test` runs something: Mocha with the `should` assertions already in `devDependencies`, running each chain with `.run(req)` against plain request objects so no Mongo is needed, covering the 31 percent total, the routing number that used to backtrack, a non-numeric `userId` and an off-site `url`. It runs `npm test`, the `jshint` task that `grunt precommit` uses with the repository's `.jshintrc`, starts Mongo from `docker-compose.yml` with `npm run start-infra`, and runs the Cypress specs for the pages it touched where the sandbox's browser allows, reporting any spec it could not run rather than omitting it.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add input validation to this Express app and open a pull request. Read server.js, package.json, Gruntfile.js, Dockerfile, app/routes/index.js, every file under app/routes and app/data, the views under app/views, config/config.js and config/env/all.js first. Use express-validator at a version that runs on the Node version the Dockerfile pins. Write one validation chain per route that reads req.body, req.params or req.query, remove every eval used to parse input, replace the backtracking bank routing regex with an anchored one, restrict the learn redirect to same-origin paths, and on failure re-render the route's view with the updateError the templates already show. Create test/unit with Mocha tests that run each chain against plain request objects without a database. Run npm test and the jshint task, start Mongo with the compose file and run the Cypress specs for the changed pages where possible, and put the output in the pull request description.",
  "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 on its own branch. The diff adds `app/routes/validators.js` and `test/unit/validators-test.js`, edits `contributions.js`, `profile.js`, `allocations.js`, `memos.js`, `session.js` and the `/learn` route in `index.js`, and adds `express-validator` to `package.json` and `package-lock.json`. The views are unchanged because the handlers reuse the `updateError` variable they already render.

The run's record keeps the `npm test` output showing the new unit target running under `grunt`, the `jshint` result, and the Cypress run for the contributions, profile, allocations and memos specs when the sandbox could start Mongo and the browser, so a reviewer sees which pages were exercised end to end.

Before merging, a reviewer checks that each field's rule matches what the view and the DAO expect, that the `/learn` restriction does not break a legitimate link the dashboard uses, and that a validation failure never reaches the DAO with partially parsed values.

## Run it on every new route merged

A repository webhook on your server can send this request whenever a pull request that adds a handler under `app/routes` is merged, with the prompt naming the new file. Each run writes the chain for that route and its unit test, so validation keeps pace with the routes instead of being audited later.

The key's `webhook_url` receives `run.completed` when the turn ends, with `data.session_url` for the pull request link; a `request_id` in the body makes a retry safe.

## Why run it on Rush?

Validation added by hand tends to cover the fields someone remembered, and the rule most likely to be wrong is the regular expression nobody tested with hostile input. In a Rush sandbox the agent reads every handler and view, runs the chains against bad input in the unit tests, and starts the app with Mongo to click through the pages, keeping the output with the pull request.

The change touches six handlers, a new module, the test setup and the dependency list, on a Node version old enough to limit library choices. One run returns all of it with its log, and the same prompt runs against every Express service in the org at once, each in its own sandbox reading its own routes.

## Frequently asked questions

### Why express-validator and not a schema library?

The `Dockerfile` pins `node:12-alpine`, and `express-validator` 6 runs there while newer schema libraries assume a later runtime. Its chains also fit the handler style in `app/routes`, where each route is a function on a handler object, and `.run(req)` lets the unit tests exercise a chain without starting Express.

### Does this fix the security issues NodeGoat teaches?

It removes the `eval` injection in contributions, the ReDoS regex in profile and the open redirect on `/learn`, and it rejects a non-numeric `userId` on allocations. It does not change the authorization check there, which takes the id from the URL rather than the session; that is a separate change the pull request notes.

### Will the forms look different?

No. The handlers re-render the same Swig views with the `updateError` variable `contributions.html` and `profile.html` already display, and the field values are echoed back so the user does not retype them. The message text names the failing field.

### Why create test/unit?

`Gruntfile.js` points `mochaTest:unit` at `test/unit/*.js`, so `npm test` has been passing with nothing to run. The new directory gives `grunt test` real cases for every chain, and they need no database or browser, unlike the Selenium and Cypress suites.

## More Node.js jobs

- [Move Express Sessions from MemoryStore to MongoDB in a Node.js App](https://getrush.ai/run/add-mongo-session-store/nodejs/)
- [Set Up npm Trusted Publishing for a Node.js Package](https://getrush.ai/run/add-npm-trusted-publishing/nodejs/)
- [Add Rate Limiting to a Node.js Login Route](https://getrush.ai/run/add-rate-limiting/nodejs/)

## The same job on other stacks

- [Add Input Validation to a Quarkus REST API](https://getrush.ai/run/add-input-validation/quarkus/)
- [Add Input Validation to a Sequelize and Express API](https://getrush.ai/run/add-input-validation/sequelize/)
- [Add Request Validation to a Serverless API](https://getrush.ai/run/add-input-validation/serverless/)

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