# Add Rate Limiting to better-auth Sign-In

Yes. An agent turns on better-auth's rate limiter with database storage and a rule for your sign-in route, proves the 429 and opens a pull request.

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

## What the agent does

The agent reads how auth is wired before touching a limit. In a monorepo like t3-oss/create-t3-turbo, `packages/auth/src/index.ts` exports `initAuth`, which builds `betterAuth` with `drizzleAdapter(db, { provider: "pg" })`, the `oAuthProxy` and `expo()` plugins plus any `extraPlugins`, a Discord social provider and `trustedOrigins: ["expo://"]`; there is no `rateLimit` block and no `appName`. `apps/nextjs/src/auth/server.ts` calls it with `nextCookies()` and a `baseUrl` chosen from `VERCEL_ENV`, and the Expo app's `apps/expo/src/utils/auth.ts` builds its client with `expoClient` against the same server. `packages/auth/package.json` has a `generate` script, `pnpx @better-auth/cli generate --config script/auth-cli.ts --output ../db/src/auth-schema.ts`, and `packages/db/src/auth-schema.ts` holds the `user`, `session`, `account` and `verification` tables it produced. `pnpm-workspace.yaml` pins `better-auth` to `1.4.0-beta.9` in its catalog, and `.github/workflows/ci.yml` runs lint, format and typecheck after `cp .env.example .env`.

better-auth's limiter is on by default only in production, with a 10-second window of 100 requests kept in memory, plus a built-in rule of 3 per 10 seconds on `/sign-in/email`. Two things about this app make that not enough. The server runs on Vercel, where memory is per function instance, so a burst spread across instances is never counted as one. And the app's only sign-in is `/sign-in/social`, which has no built-in rule. So the agent adds `rateLimit` to the `initAuth` config: `enabled: true`, `storage: "database"`, and `customRules` with a tight window on `/sign-in/social` at the count the prompt names, leaving the general default for everything else. It sets `appName` while it is there, and leaves `advanced.ipAddress.ipAddressHeaders` at its default, naming it in the pull request as the setting to change if a proxy in front of the app puts the client address in another header.

Database storage needs a table. `pnpm auth:generate` rewrites `packages/db/src/auth-schema.ts` with the `rateLimit` table beside the four existing ones, and `pnpm db:push` applies it, the same way the template applies every other schema change. On the client side, `apps/nextjs/src/auth/client.ts` and the Expo client get a `fetchOptions.onError` that reads a 429 and its `X-Retry-After` header and shows how long to wait, so a limited user sees a message instead of a silent failure.

Then it proves the rule. In the sandbox the agent copies `.env.example` to `.env`, runs `pnpm install`, `pnpm typecheck` and `pnpm lint`, and starts `pnpm dev:next`. A loop of requests to `/api/auth/sign-in/social` with `{"provider": "discord"}` shows the first answers come from the handler and every answer after the rule's count, inside the window, is a 429 carrying `X-Retry-After`; the loop output, with status codes and that header, goes into the pull request. The generated table is in the diff, and applying it to your database is `pnpm db:push` after the merge.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add rate limiting to better-auth in packages/auth/src/index.ts. Enable it explicitly with storage set to database, add a custom rule for /sign-in/social of 5 requests per 10 seconds, and set appName. Regenerate the auth schema with pnpm auth:generate so the rateLimit table lands in packages/db/src/auth-schema.ts. In the Next.js and Expo auth clients, handle a 429 by reading X-Retry-After and surfacing the wait. Run pnpm typecheck and pnpm lint. Start the Next.js app and prove the rule with a loop of requests to /api/auth/sign-in/social, quoting the status codes and the X-Retry-After header once the limit is hit. Open a pull request with the loop output and say that pnpm db:push applies the new table.",
  "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 changes `packages/auth/src/index.ts` (the `rateLimit` block and `appName`), `packages/db/src/auth-schema.ts` (the generated `rateLimit` table), `apps/nextjs/src/auth/client.ts` and `apps/expo/src/utils/auth.ts` (the 429 handling). Its description quotes the request loop with the point where answers turn to 429 and the `X-Retry-After` value, and the typecheck and lint results.

A reviewer checks that the custom rule names the path the app actually uses for sign-in, that the general limit was not loosened, and that the generated schema file changed only by the new table, since `auth:generate` rewrites the whole file. The transcript at GET /o/{org}/sessions/{id}/messages has the dev server start and every request of the loop with its status.

Your database is not touched. The table is created by `pnpm db:push` against your own `POSTGRES_URL` after the merge, and until then the limiter is not live anywhere.

## Run it on every Linear issue labelled security

Add an automation on the Project with a `linear` trigger on `linear.issue.labeled` and the label your security work uses, with this prompt as its text. When someone labels an issue describing a limit (a password endpoint, an OTP route, a public form), the run starts with the issue as its context, does the work in the Project's repository and opens a pull request that links back to it. The trigger adds the issue after the prompt and fills in no placeholder, and a change made by an app integration never fires it.

From your own backlog tool, the same run starts with this body and the issue URL in `resources`, with a `request_id` that is a UUID v5 of the issue id so a retried delivery returns the run already begun. The automation's `max_runs_per_hour` holds a burst of labels to that many runs an hour.

## Why run it on Rush?

A rate limit that was never hit is a guess. The convincing part of this change is a server running the new config and a loop of real requests turning into 429s at the configured count with a `Retry-After` the client can read, and that is a dev server, a database schema and a shell loop that nobody wants on a laptop between other work. The sandbox has all three for the run, and the loop's output is in the transcript.

The same rule belongs in every app that uses the auth package, and several apps are several runs on their own branches, each with its own loop output. A reviewer reads one diff per app and one piece of evidence per diff.

## Frequently asked questions

### Why database storage rather than memory?

The app deploys to Vercel, where each function instance has its own memory, so an attacker whose requests land on different instances never reaches a memory-kept limit. The `rateLimit` table makes the count shared. If you run Redis, say so in the prompt and the agent uses `secondary-storage` instead, which needs no new table.

### Does the limit apply to the Expo app too?

Yes. The Expo client calls the same Next.js auth routes over HTTP, so a burst from a phone counts like one from a browser. That is why the Expo client gets the 429 handling as well; server-side calls through `auth.api` are not limited.

### What about the built-in sign-in rule?

better-auth already limits `/sign-in/email` to 3 requests per 10 seconds, but this app signs in with Discord through `/sign-in/social`, which has no built-in rule. The custom rule covers that path; the email rule stays in place for the day email sign-in is added.

### Will it lock out real users behind one office address?

A limit keyed on IP treats everyone behind a NAT as one client. The window is short, so a team signing in at once is unlikely to collide, but the count is yours to set in the prompt. Behind a proxy that puts the client address in another header, `advanced.ipAddress.ipAddressHeaders` names which header to read.

## The same job on other stacks

- [Add Rate Limiting to a Go chi API](https://getrush.ai/run/add-rate-limiting/chi/)
- [Add Rate Limiting to a Cloudflare Worker](https://getrush.ai/run/add-rate-limiting/cloudflare-workers/)
- [Add Rate Limiting to a CodeIgniter 4 App](https://getrush.ai/run/add-rate-limiting/codeigniter/)
- [Add Rate Limiting to a Django REST Framework API](https://getrush.ai/run/add-rate-limiting/django-rest-framework/)
- [Add Rate Limiting to a .NET Minimal API](https://getrush.ai/run/add-rate-limiting/dotnet/)
- [Add Rate Limiting to an Echo API](https://getrush.ai/run/add-rate-limiting/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/)
