# Add Response Compression to a Fastify App

Yes. An agent adds @fastify/compress as an autoloaded plugin to your Fastify app, keeps the gzipped CSV route single-encoded, tests Accept-Encoding and opens a PR.

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

## What the agent does

The agent reads how the app is assembled before it adds a plugin. In a service shaped like fastify/demo, package.json is ESM (`"type": "module"`), depends on fastify ^5.10.0 and a set of official plugins: @fastify/cors, @fastify/helmet, @fastify/rate-limit, @fastify/static, @fastify/swagger, @fastify/swagger-ui, @fastify/under-pressure, @fastify/session, @fastify/multipart and @fastify/env, with @fastify/compress absent. src/app.ts registers @fastify/autoload three times: plugins/external first, then plugins/app, then routes with autoHooks. Every file under src/plugins/external exports the plugin as default and an `autoConfig` that autoload passes as options: cors.ts lists the allowed methods, rate-limit.ts reads `fastify.config.RATE_LIMIT_MAX` from the @fastify/env schema in env.ts, and under-pressure.ts wraps the plugin in fastify-plugin and declares a dependency on knex. That is the convention a new compress.ts has to follow.

It then reads what the routes send, because compression is only worth it on some of it. src/routes/api/tasks/index.ts answers `GET /api/tasks` with a paginated JSON page validated by a TypeBox response schema, and `GET /api/tasks/download/csv` already pipes a knex stream through csv-stringify and node:zlib's createGzip, with `Content-Type: application/gzip` and a Content-Disposition for tasks.csv.gz. src/routes/home.ts returns a one-line welcome object. @fastify/static serves the uploads directory, @fastify/swagger-ui serves its HTML and scripts, and src/routes/api/autohooks.ts refuses every /api route except login without a session. So the agent registers @fastify/compress globally in src/plugins/external/compress.ts with an `autoConfig` that sets the encodings in preference order and a threshold, so the welcome message and other tiny JSON bodies go out as they are. It checks that the plugin's default media-type matching leaves the application/gzip CSV body alone, and if the plugin would touch it, turns compression off on that route with the per-route option, so a download is never gzipped twice.

Tests follow the ones already there. test/app/cors.test.ts builds the app through test/helper.ts, injects a request and asserts on headers with node:test and node:assert. The agent adds test/app/compress.test.ts: a login through the helper's `injectWithLogin`, then `GET /api/tasks` with `Accept-Encoding: gzip` must answer with `content-encoding: gzip` and `vary: accept-encoding`, and gunzipping the payload must give the same JSON as the request without the header, which must carry no content-encoding at all. A third case requests the CSV route with gzip accepted and checks that one gunzip yields CSV text with the header row, not another gzip stream. A fourth asserts that a body under the threshold stays uncompressed.

Then it runs what CI runs. .github/workflows/ci.yml installs with `npm i --ignore-scripts` on Node 22 and 24, builds with `npm run build -- --noEmit`, lints with `npm run lint`, migrates and runs `npm run test`, which seeds the database and runs the files under test/ with `tsx --test` under c8, against a MySQL 8.4 service. In its sandbox the agent starts MySQL from docker-compose.yml, writes the .env that .env.example describes with a COOKIE_SECRET of at least 32 characters and RATE_LIMIT_MAX=4 as the comment asks, runs `npm run db:create`, `npm run db:migrate` and the test script, then starts the server with `npm run dev` and fetches /api/tasks with and without Accept-Encoding through curl to read the two sets of headers. .npmrc's `min-release-age=7` and `ignore-scripts=true` apply to the install of the new dependency too.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add response compression to this Fastify app. Read package.json, src/app.ts, src/server.ts, every file under src/plugins/external, src/routes/home.ts, src/routes/api/tasks/index.ts, src/routes/api/autohooks.ts, test/helper.ts, test/app/cors.test.ts, .env.example, .npmrc and .github/workflows/ci.yml first. Add @fastify/compress as an autoloaded external plugin following the autoConfig convention the other plugins use, with the encodings in preference order and a threshold so tiny JSON bodies stay uncompressed. Make sure the CSV download route, which already gzips its stream and sends application/gzip, is never compressed a second time. Add tests in test/app that log in through the helper, request /api/tasks with and without Accept-Encoding, check content-encoding and vary, decompress and compare the JSON, and check the CSV route still yields CSV after one gunzip. Start MySQL from docker-compose.yml, write the .env from .env.example, run the build with --noEmit, the lint and the full test script as CI does, start the server and fetch /api/tasks twice with curl to capture the headers, and open a pull request that quotes the test output and both sets of headers.",
  "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 with four changed files: package.json and package-lock.json with @fastify/compress added to dependencies, src/plugins/external/compress.ts with its `autoConfig`, and test/app/compress.test.ts. Nothing under src/routes changes unless the CSV route needed the per-route opt-out, and src/app.ts is untouched because autoload picks the new file up.

The description quotes the test run from the sandbox with the new cases listed among the existing app tests, and the response headers of the same `GET /api/tasks` fetched twice, once with Accept-Encoding and once without, so a reviewer sees content-encoding and vary appear only on the first. It also shows the gunzipped header row from the CSV download route, proving that path kept a single layer of gzip.

Before merging, a reviewer decides the encoding order (brotli makes smaller bodies but costs more CPU per response on a service that already runs under-pressure limits), the threshold, and whether anything served by @fastify/static should be excluded because uploaded files are not compressible. Changing any of these is a follow-up on the same session, where the sandbox still has MySQL running.

## Run it on every Fastify service answering uncompressed

This is a change to start from the terminal and pick up later: one `POST /o/{org}/sessions` with this prompt and the repository in `resources`, then the laptop closes. The run reads the plugin convention, adds the file, runs the suite against MySQL and opens the pull request without anyone watching. The sandbox parks with its disk when the turn ends, so a follow-up such as `drop brotli and keep gzip only` wakes it with node_modules, the database and the branch intact.

A team with several Fastify services sends the same body once per repository, one run each, and each run reads that service's own plugin directory and routes. Give the API key a `webhook_url` and Rush posts `run.completed` or `run.failed` with the `session_url` when each turn ends, so the pull request links collect in one place. Send a `request_id` so a retried POST returns the run it already started instead of a second one.

## Why run it on Rush?

Compression is cheap to add and easy to get wrong in ways that only show on a real response: a CSV gzipped twice, a missing `Vary` header so a cache hands gzip to a client that cannot read it, or a plugin registered after the routes so it never applies. The agent does it against the running service with MySQL beside it, and the pull request carries the headers it saw rather than a description of what the plugin is supposed to do.

The run's record keeps every command: the install under the repository's .npmrc, the build with --noEmit, the lint, the test run and the curl calls, so a reviewer who wants to know whether the threshold was exercised can read it. Nothing happens on the reviewer's laptop, and the branch is ready for CI on Node 22 and 24 as the matrix already runs.

## Frequently asked questions

### Will the CSV download be compressed twice?

No. The route sets Content-Type to application/gzip and pipes through createGzip itself; @fastify/compress compresses only the media types it is configured for, and the agent adds a test that gunzips the download once and expects CSV text. If your fork changed that route's content type, the agent opts the route out explicitly.

### Does it fit the autoload setup?

Yes. The plugin goes in src/plugins/external like cors.ts and helmet.ts, exporting the plugin as default and its options as autoConfig, so app.ts needs no change. External plugins load before routes, so every route registered later is covered.

### Which encodings does it enable?

The pull request lists them in autoConfig in the order the server prefers when a client accepts several. gzip and deflate are in Node's zlib and so is brotli; the reviewer can drop brotli if CPU matters more than body size. The order is one line to change.

### Can I compress only some routes instead?

Yes. @fastify/compress can be registered with its global hook off and applied per route, or inside an encapsulated plugin. The agent registers it globally because the JSON API is where the bytes are, and the description says how to narrow it.

### Does it need Redis or another service?

No. Compression runs in the Node process. The tests need MySQL only because the existing test script seeds the database before every run.

## More Fastify jobs

- [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/)
- [Add Health Checks to a Fastify App](https://getrush.ai/run/add-health-checks/fastify/)

## The same job on other stacks

- [Add Response Compression to a Fiber App](https://getrush.ai/run/add-compression/fiber/)
- [Add Compression to a Koa App](https://getrush.ai/run/add-compression/koa/)
- [Add Response Compression to a Ktor API](https://getrush.ai/run/add-compression/ktor/)

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