# Add an Audit Log to a Fastify API

Yes. An agent adds an audit_log table, records who changed each task and how in a Fastify hook, exposes it to admins, tests it with node:test, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-audit-log/fastify/). 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 the API is put together, because an audit log has to sit where every mutation already passes. In a Fastify API shaped like fastify/demo, `package.json` pins `fastify ^5.10.0` with `@fastify/autoload`, `@fastify/session`, `@fastify/type-provider-typebox`, `knex` on `mysql2`, and `postgrator` for the numbered SQL files in `migrations/`. `src/app.ts` autoloads `src/plugins/external`, then `src/plugins/app`, then `src/routes` with `autoHooks` on, and `src/routes/api/autohooks.ts` rejects any unauthenticated request outside `/api/auth/login`, so `request.session.user` is set on every route the log cares about. `src/routes/api/tasks/index.ts` holds the mutations: `POST /`, `PATCH /:id`, `DELETE /:id` behind `request.isAdmin`, `POST /:id/assign` behind `request.isModerator`, and the upload and image routes.

It adds `migrations/006.do.audit_log.sql` and its `undo` pair, following the `002.do.tasks.sql` shape: an `audit_log` table with `id`, `actor_id` referencing `users(id)`, `entity` and `entity_id`, `action`, a `changes` JSON column, and `created_at` defaulting to `CURRENT_TIMESTAMP`. The repository goes in `src/plugins/app/audit/audit-repository.ts` as a `fastify-plugin` that depends on `knex`, like `tasks-repository.ts`, with `record()` and `paginate()` methods. The schema for a log row goes in `src/schemas/audit.ts` in TypeBox, so the response is validated and shows up in Swagger under its own tag.

Rather than editing each handler, the agent writes the recording in one place. In `src/routes/api/tasks/index.ts` the `POST`, `PATCH`, `DELETE` and `assign` routes gain an `onSend` hook scoped to that plugin, which fires only when the reply status is below 400 and calls `auditRepository.record()` with `request.session.user.id`, the task id from `request.params` or the created id in the payload, the method mapped to `create`, `update`, `delete` or `assign`, and the request body as `changes`. The read-only routes are left alone. A new `src/routes/api/audit/index.ts` exposes `GET /api/audit` with `page` and `limit` query parameters and the `preHandler: (request, reply) => request.isAdmin(reply)` pattern the delete route already uses.

Tests follow `test/routes/api/tasks/tasks.test.ts`: `build()` from `test/helper.ts`, `app.injectWithLogin('admin@example.com', …)` for the session cookie, and rows inserted with `app.knex`. The new `test/routes/api/audit/audit.test.ts` creates a task through the API, patches it, checks one `create` and one `update` row exist with the right `actor_id`, checks that a moderator gets `403` from `GET /api/audit`, and checks a failed `PATCH` on a missing id writes nothing. The agent runs `npm run db:migrate`, `npm run lint`, `npm run build -- --noEmit` and `npm test` against the `mysql:8.4` container from `docker-compose.yml`, the same steps `.github/workflows/ci.yml` runs on Node 22 and 24.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add an audit log to this Fastify API and open a pull request. Read package.json, src/app.ts, src/routes/api/autohooks.ts, src/routes/api/tasks/index.ts, src/plugins/app/tasks/tasks-repository.ts, src/plugins/app/authorization.ts, src/schemas/tasks.ts, migrations/002.do.tasks.sql, test/helper.ts, test/routes/api/tasks/tasks.test.ts, docker-compose.yml and .github/workflows/ci.yml first. Add migrations/006.do.audit_log.sql and 006.undo.audit_log.sql creating audit_log with id, actor_id referencing users(id), entity, entity_id, action, a JSON changes column and created_at. Add src/plugins/app/audit/audit-repository.ts as a fastify-plugin depending on knex, with record() and paginate(). Add src/schemas/audit.ts in TypeBox. In src/routes/api/tasks/index.ts, record create, update, delete and assign through one onSend hook that only writes on 2xx responses, using request.session.user.id as the actor. Add src/routes/api/audit/index.ts with GET /api/audit, paginated, admin only via request.isAdmin. Add test/routes/api/audit/audit.test.ts using build() and injectWithLogin from test/helper.ts: a task created then patched leaves one create and one update row with the right actor_id, a moderator gets 403 from GET /api/audit, and a failed PATCH writes nothing. Run npm run db:migrate, npm run lint, npm run build -- --noEmit and npm test against the docker-compose MySQL, and paste the output in the pull request. Do not change the existing route schemas or the login flow.",
  "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 with two migration files, `audit-repository.ts` under `src/plugins/app/audit/`, `src/schemas/audit.ts`, the hook in `src/routes/api/tasks/index.ts`, the admin-only `src/routes/api/audit/index.ts`, and `test/routes/api/audit/audit.test.ts`. The description lists the columns, which routes write which `action`, and the output of `npm run lint`, the `tsc --noEmit` build and `npm test` with the `c8` coverage table from the sandbox.

The repository's CI runs the same `npm run build -- --noEmit`, `npm run lint` and `npm test` on the pull request against the `mysql:8.4` service on Node 22 and 24, so a migration that fails under Postgrator or a type the TypeBox schema does not accept shows up as a red check rather than after merge.

A reviewer checks that the hook writes only on success, that the actor comes from the session and never from the body, that `GET /api/audit` is behind `isAdmin` and paginated with the same `page` and `limit` names the tasks list uses, and that the `undo` migration drops the table cleanly. Then they decide whether `changes` should also hold the previous values, which the prompt leaves out on purpose.

## Run it on every service that handles customer data

A team with several Fastify services sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own routes and session plugin, so a service that authenticates with a JWT header instead of `@fastify/session` gets the actor from its own request decorator, and each opens its own pull request.

Give the API key a `webhook_url` and Rush POSTs `run.completed` to it when each turn ends, with a `session_url` to read the pull request from, so a script can list the open audit-log pull requests in one place.

## Why run it on Rush?

An audit log is easy to describe and tedious to prove: the proof is the row that appears after a real `PATCH` and the row that does not appear after a `404`. In a Rush sandbox the agent brings up the `mysql:8.4` container from `docker-compose.yml`, runs the Postgrator migration, drives the API through `app.inject` with a real session cookie, and keeps every command and its output in the run's record, so the pull request shows the rows, not a claim about them.

The work passes the repository's own gates before anyone reads it: `neostandard` lint, the TypeScript build, and the `node:test` suite under `c8`. The same request body works unchanged on the next Fastify service, and each run opens its own pull request on its own branch.

## Frequently asked questions

### Why an onSend hook instead of a call in each handler?

Because the routes already share one plugin file, a hook scoped to it covers `POST`, `PATCH`, `DELETE` and `assign` without touching each handler's body, and it can check `reply.statusCode` so a `404` or a validation `400` writes nothing. The read-only `GET` routes stay out of the log because the hook maps only the mutating methods.

### Does it work with MySQL and the Postgrator migrations?

Yes. The demo stores migrations as numbered `.do` and `.undo` SQL files run by `scripts/migrate.ts` through the `mysql` driver, so the agent adds `006.do.audit_log.sql` and `006.undo.audit_log.sql` in that format and uses MySQL's `JSON` type for `changes`.

### Who can read the log?

Only users with the `admin` role, through the same `request.isAdmin(reply)` preHandler that guards `DELETE /api/tasks/:id`. Moderators and plain users get `403`, and the test asserts it.

### Will the existing tests still pass?

The hook only adds a row after a successful mutation, so the task tests in `test/routes/api/tasks/tasks.test.ts` see the same responses. The agent runs the full `npm test`, which seeds the database first, and pastes the result in the pull request.

## More Fastify jobs

- [Add Response Compression to a Fastify App](https://getrush.ai/run/add-compression/fastify/)
- [Add CSRF Protection to a Fastify App](https://getrush.ai/run/add-csrf-protection/fastify/)
- [Switch a Fastify API From Offset to Cursor Pagination](https://getrush.ai/run/add-cursor-pagination/fastify/)

## The same job on other stacks

- [Add an Audit Log to a Filament Admin Panel](https://getrush.ai/run/add-audit-log/filament/)
- [Add an Audit Log to a Mongoose and Express API](https://getrush.ai/run/add-audit-log/mongoose/)
- [Add an Audit Log to a Prisma Project](https://getrush.ai/run/add-audit-log/prisma/)

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