# Add Response Caching to a Hono API

Yes. An agent adds Hono's cache middleware to the GET routes of your Workers API, invalidates on writes, adds ETags, tests it in the Workers pool and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-caching/hono/). 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 where each read route gets its data, because caching a response is only worth it when the work behind it is real. In the `blog` workspace of honojs/examples, `src/api.ts` registers `GET /`, `GET /posts`, `POST /posts` and `GET`, `PUT` and `DELETE /posts/:id` on `new Hono<{ Bindings: Bindings }>()` with `cors()` on `/posts/*`, and `src/model.ts` stores each post in KV under the `v1:post:` prefix: `getPosts` calls `KV.list` and then `KV.get` once per key in a loop, so a list of fifty posts is fifty-one KV reads on every request. `src/bindings.ts` names `USERNAME`, `PASSWORD` and the `BLOG_EXAMPLE` namespace, and `src/index.ts` mounts the API under `/api` behind `prettyJSON` and basic auth on every non-GET request to `/posts/*`.

The test setup decides how the change can be proved. `package.json` depends on `hono` with a caret on 4.2.4 and tests with `vitest` 1.3.0 through `@cloudflare/vitest-pool-workers`; `vitest.config.ts` calls `defineWorkersConfig` with `isolatedStorage: false` and `wrangler.configPath` set to `./wrangler.toml`, which the README says to create from `wrangler.example.toml`. `src/api.test.ts` imports `env` from `cloudflare:test` and calls `worker.request('/posts', {}, env)` directly on the API app, so the `/api` prefix from `index.ts` is absent in tests. The root `package.json` lists the workspaces under `npm@10.0.0`.

The agent applies `cache` from `hono/cache` to `GET /posts` and `GET /posts/:id` with a named cache and a `cacheControl` of `public, max-age=60`, adds `etag()` from `hono/etag` so a client that already has the body gets a 304, and leaves `GET /` and every write route uncached. The middleware stores only responses whose `ok` is true, so a 404 for a missing post is never kept. In the `POST`, `PUT` and `DELETE` handlers, after the KV write succeeds, the agent opens the same named cache with `caches.open` and deletes the entries for the list and for that post. The cache key is the full request URL, and in production the app lives under `/api`, so the agent derives the keys from `c.req.url` rather than hard-coding a path, and that one detail is what the tests pin down.

Tests go next to the existing ones in `src/api.test.ts`, under the Workers pool where the Cache API is implemented: a second `GET /posts` after the first returns the same body without a KV read, checked by spying on `env.BLOG_EXAMPLE.get`; a `POST /posts` followed by `GET /posts` shows the new post, proving the invalidation; a `GET` with the returned `ETag` in `If-None-Match` gets 304; and `beforeEach` clears the named cache because `isolatedStorage: false` keeps it across tests. The agent runs `npm test -w blog` and `tsc --noEmit` with the `tsconfig.json` that loads `vitest/globals`, the experimental Workers types and the vitest pool types.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add response caching to the blog workspace of this repository and open a pull request. Read the root package.json, blog/package.json, blog/src/index.ts, blog/src/api.ts, blog/src/model.ts, blog/src/bindings.ts, blog/src/api.test.ts, blog/vitest.config.ts, blog/tsconfig.json and blog/README.md first. Apply the hono/cache middleware with a named cache and a short public max-age to GET /posts and GET /posts/:id, add the etag middleware to the same routes, and leave the root route and all write routes uncached. After each successful POST, PUT and DELETE, delete the list entry and the post's entry from the named cache, building the keys from the request URL so the /api prefix in index.ts is respected. Add tests in the Workers pool that prove the second read skips KV, a write invalidates the list, and an If-None-Match request gets 304, clearing the cache before each test. Run the tests and the TypeScript check 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 changes `blog/src/api.ts` to add the two middlewares on the read routes and the invalidation in the three write handlers, adds a small helper for the cache keys, and extends `blog/src/api.test.ts` with the four cases and the `beforeEach`. `model.ts`, `bindings.ts` and `index.ts` are unchanged, and the description lists the `Cache-Control` value so the team can decide the age.

The run's record keeps the `npm test -w blog` output from the Workers pool and the `tsc --noEmit` result, so a reviewer can see the KV spy count drop to zero on the second read and the 304 case pass, rather than inferring it from the diff.

Before merging, a reviewer checks that the cache name is unique to this Worker, that the invalidation keys match the URLs clients actually request including `/api`, that `cors()` still sets its headers on a cached response, and that a 60-second window is acceptable for the list after a write from another path.

## Run it on every new read endpoint

A team adding routes to several Hono services starts one run per repository with `POST /o/{org}/sessions`, this prompt with the workspace and routes swapped in, and the repository in `resources`. Each run reads its own model, so a route backed by D1 or an upstream fetch gets the same middleware with a key and age that fit, and each opens its own pull request with its own test output.

The key's `webhook_url` receives `run.completed` for each run it starts, with `data.session_url` for the pull request link.

## Why run it on Rush?

Caching is easy to add and hard to trust: the first bug is a stale list after a write, the second is a key that differs between tests and production because of a mount prefix. In a Rush sandbox the agent runs the Workers test pool, where the Cache API behaves as it does at the edge, spies on the KV binding to count reads, and keeps the output with the pull request.

The change is small but touches every handler in the file and the test setup. One run returns it with proof, and the same prompt runs across every Hono service in the org at once, each in its own sandbox reading its own routes and bindings.

## Frequently asked questions

### Does hono/cache work outside Cloudflare Workers?

It uses the `caches` global, which Workers and Deno provide and Node and Bun do not. This app runs under `wrangler`, and its tests run in the Workers pool, so both have it. For a Node deployment the agent would wrap the middleware in a check and say so in the pull request.

### What happens to the basic auth on writes?

Nothing changes. `index.ts` still runs `basicAuth` for every non-GET request to `/posts/*` before the API routes, and only GET responses are cached, so a cached body is never served in place of an authentication check.

### Why delete entries instead of lowering max-age?

A short `max-age` alone still serves a stale list for up to that long after a `POST`. Deleting the list entry and the post's entry in the write handlers makes the next read fresh at once, and the test that posts then reads proves it. The `max-age` then only bounds reads nobody invalidated.

### Will the ETag change the existing clients?

Only for clients that send `If-None-Match`; they get a 304 with no body and keep what they have. Everyone else receives the same JSON with one more header. The CORS middleware on `/posts/*` is unchanged, so browsers see the same allowed headers as before.

## More Hono jobs

- [Add CORS to a Hono API](https://getrush.ai/run/add-cors/hono/)
- [Add a Cron Trigger to a Hono Worker](https://getrush.ai/run/add-cron-trigger/hono/)
- [Add CSRF Protection to a Hono App with Cookie Sessions](https://getrush.ai/run/add-csrf-protection/hono/)

## The same job on other stacks

- [Add HTTP Caching to a Ktor API](https://getrush.ai/run/add-caching/ktor/)
- [Add Caching to a Quarkus App](https://getrush.ai/run/add-caching/quarkus/)
- [Add Caching to a Streamlit App](https://getrush.ai/run/add-caching/streamlit/)

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