# Add Rate Limiting to a Node.js Login Route

Yes. An agent adds a limiter to the login and signup routes of an Express app, keyed by client address with limits read from config, tests it and opens a PR.

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

## What the agent does

The agent starts by reading how requests reach the login handler. In an app shaped like OWASP/NodeGoat, `server.js` connects to MongoDB with the `mongodb` driver, registers `body-parser`, `express-session` with `saveUninitialized: true` and `resave: true`, the Swig view engine through `consolidate`, static assets from `app/assets`, and then calls `routes(app, db)` before `http.createServer(app).listen(port)`. `package.json` pins `express` ^4.13.4 and `express-session` ^1.13.0, and `helmet` ^2.0.0 is installed but every `helmet` line in `server.js` is commented out. `config/env/all.js` exports `port` (4000 by default), `db`, `cookieSecret`, `hostName` and `environmentalScripts`, and `config/config.js` merges it with the file for `NODE_ENV`. `app/routes/index.js` maps `POST /login` to `sessionHandler.handleLoginRequest` and `POST /signup` to `sessionHandler.handleSignup`; nothing in front of either counts attempts, so a script can try passwords against `/login` as fast as the server answers.

`app/routes/session.js` is where the handler renders `login.html` with a `loginError` string, and its comments spell out the training app's intent: separate messages for an unknown user and a wrong password, which a limiter should not make worse. The agent adds `express-rate-limit` as a dependency after checking its `engines` field against the `node:12-alpine` base in the `Dockerfile` and the `10.x`, `12.x` and `14.x` matrix in `.github/workflows`, and pins the newest major those versions run. It writes `app/middleware/rate-limit.js`, which builds two limiters from new `loginRateLimit` and `signupRateLimit` entries in `config/env/all.js`, each with a `windowMs` and a `max`, so the values sit beside `port` and `cookieSecret` where the rest of the configuration lives and a deployment can override them in `config/env/production.js`.

The limiters key on `req.ip`. Because the app listens on plain HTTP and the `docker-compose.yml` publishes `4000:4000` with no proxy, the agent leaves `trust proxy` unset and says so in the pull request, with the one line to add when a load balancer sits in front. A blocked login request does not get the library's default plain-text body: the handler option renders `login.html` with `loginError` set to a message about too many attempts and the `userName` echoed back, the way `handleLoginRequest` already does, and the `429` status and `Retry-After` header the library sets stay on the response. The same shape applies to `signup.html`. `app/routes/index.js` gains `loginLimiter` and `signupLimiter` as the first argument on the two `POST` routes, and the `GET` routes that render the forms are left alone.

Tests go where the repository already looks for them. `Gruntfile.js` runs `mochaTest:unit` over `test/unit/*.js`, a directory that does not exist yet, so `npm test` currently runs nothing. The agent creates `test/unit/rate-limit-test.js` using the `mocha` and `should` already in `devDependencies`: it mounts the limiter on a bare Express app with a stub handler, sends `max` requests from one address with Node's `http` module, asserts the next one is `429` with a `Retry-After` header, and asserts a request from another address still gets through. Then it runs `npm test`, `grunt precommit` for `jsbeautifier` and `jshint`, and starts the server against the `mongo` service from `docker-compose.yml` to paste a real `curl -i` exchange into the description.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add rate limiting to the login and signup routes of this Express app and open a pull request. Read package.json, server.js, config/config.js, config/env/all.js, app/routes/index.js, app/routes/session.js, app/views/login.html, Gruntfile.js, Dockerfile and .github/workflows first. Add express-rate-limit, choosing a major whose engines field supports the Node versions in the Dockerfile and the workflow matrix. Write app/middleware/rate-limit.js exporting loginLimiter and signupLimiter built from loginRateLimit and signupRateLimit objects (windowMs, max) that you add to config/env/all.js; key on req.ip and do not set trust proxy, but say in the pull request what to set behind a proxy. When a request is blocked, render the same login or signup view with the error string the view already shows, keeping the 429 status and Retry-After header. Apply the limiters only to POST /login and POST /signup in app/routes/index.js. Add test/unit/rate-limit-test.js with mocha and should, since Gruntfile.js runs mochaTest:unit over test/unit and that directory is empty: cover the block after max attempts from one address, the Retry-After header, and a second address getting through. Run npm test and grunt precommit, start the server and include a curl -i exchange showing the 429 in the pull request. Do not change the session or authentication code.",
  "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 `app/middleware/rate-limit.js` and `test/unit/rate-limit-test.js`, adds one dependency to `package.json` and `package-lock.json`, two configuration objects to `config/env/all.js`, and two middleware arguments to `app/routes/index.js`. The description shows the `npm test` output for the new unit file, the `jshint` result from `grunt precommit`, and a `curl -i` transcript in which the request after the limit answers `429` with `Retry-After` and the login page body.

On a repository with this `E2E Test` workflow, the pull request runs the Cypress specs under `test/e2e/integration` on three Node versions against a `mongo:4.0` container. `login_spec.js` and `signup_spec.js` submit the forms a handful of times, well under the configured `max`, so they pass unchanged; if the agent's chosen window is shorter than a spec's run it says so and raises the value rather than skipping a spec.

A reviewer checks three things before merging: that the `max` and `windowMs` values suit real users who mistype a password, that `req.ip` is the right key for how the app is deployed, and that the rendered error page carries no hint about whether the user name exists. Then they decide whether the same limiter belongs on `POST /profile` and `POST /memos`, which the pull request leaves alone.

## Run it on every new Express service

A team with several Express services sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own `server.js` and route table, so a service that already mounts a limiter gets its window and key reviewed instead of a second limiter, and a service behind a proxy gets `trust proxy` set in the same change. Each run ends in its own pull request with its own unit test.

Set a `webhook_url` on the API key and Rush POSTs `run.completed` to it when each turn finishes, with the `session_url` to read the pull request link from, so a handler on your server can post it where that service's owners review.

## Why run it on Rush?

A limiter is a small change with a loud failure mode: the wrong key blocks a whole office behind one NAT address, and the wrong body turns the login page into a plain-text error. In a Rush sandbox the agent installs the package against the repository's own Node version, starts the server with the `mongo` service from `docker-compose.yml`, and sends real requests with `curl`, and every command and its output stays in the run's record, so the pull request shows the exact `429` exchange a user would see.

The repository's own checks are a Grunt unit task that has had no files to run, `jshint`, and a Cypress suite on three Node versions. The agent runs the first two before pushing and reads the Cypress specs to keep its limits above what they send, so the pull request opens green rather than after a round of CI failures. The same request body works on every Express service a team owns.

## Frequently asked questions

### Why express-rate-limit and not a Redis-backed limiter?

The app runs as one process in the `Dockerfile` and `docker-compose.yml`, so an in-memory store counts every request it sees. The library takes a store option, and the pull request names the Redis store to add when the service runs more than one replica, without adding Redis to a repository that does not have it.

### Will this break the Cypress login tests?

No. The specs under `test/e2e/integration` submit the login and signup forms a few times per run, under the `max` the agent configures. The agent reads them before choosing values and says in the pull request how many attempts each spec makes.

### Does it limit by user name as well as by address?

The default keys on `req.ip` only, because keying on the submitted user name lets an attacker lock a victim out by sending wrong passwords for them. If you want both, ask for a second limiter keyed on the user name with a higher `max`, and the agent adds it in the same middleware file.

### What happens behind a load balancer?

Every request would arrive from the balancer's address and share one counter. The pull request names the `trust proxy` setting to add in `server.js` and the hop count to give it, and leaves it out because the repository's Compose file has no proxy in front of the app.

## More Node.js jobs

- [Add Security Headers to a Node.js App](https://getrush.ai/run/add-security-headers/nodejs/)
- [Add Structured Logging to a Node.js App from a Linear Issue](https://getrush.ai/run/add-structured-logging/nodejs/)
- [Convert a Node.js App from JavaScript to TypeScript](https://getrush.ai/run/convert-javascript-to-typescript/nodejs/)

## The same job on other stacks

- [Add Rate Limiting to a Quarkus REST API](https://getrush.ai/run/add-rate-limiting/quarkus/)
- [Add Rate Limiting to a React Router App](https://getrush.ai/run/add-rate-limiting/react-router/)
- [Add Rate Limiting to a Rocket API](https://getrush.ai/run/add-rate-limiting/rocket/)

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