# Add Request Timeouts to a Hono App

Yes. An agent adds Hono's timeout middleware to the routes that wait on upstream calls, makes the 504 reach the client, tests it with Vitest, and opens a PR.

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

## What the agent does

The agent first finds which handlers can hang. In an app like the `basic` workspace of honojs/examples, `src/index.ts` builds one `Hono` app with `poweredBy()` on every route, `basicAuth` under `/auth/*`, `etag()` under `/etag/*`, a custom `X-Response-Time` middleware, and a `/fetch-url` route that does `await fetch('https://example.com/')` with no deadline at all: if example.com stalls, the Worker waits with it. `app.onError` catches everything and answers `Custom Error Message` with status 500, and `app.notFound` answers a custom 404. `package.json` depends on `hono` at `^4.2.4` with `vitest` `^1.5.0` and `wrangler` `^3.53.0`, scripts `dev`, `deploy` and `test` (`vitest --run`), `wrangler.toml` sets `compatibility_date = "2024-04-01"`, and the repository root is an npm workspace (`packageManager` `npm@10.0.0`) with no lockfile checked in.

Hono ships a `timeout` middleware at `hono/timeout` from version 4.4.0: `timeout(duration, exception?)` races the downstream handler against a timer and throws an `HTTPException` with status 504 and the message `Gateway Timeout` when the timer wins. With no lockfile, `npm install` already resolves `^4.2.4` to a 4.x release that has it, but the agent raises the range in `package.json` to `^4.4.0` so a fresh install can never land on a version without the import. It then adds `app.use('/fetch-url', timeout(5000))` next to the other per-path middleware and, because the timer does not stop the upstream request, passes `signal: AbortSignal.timeout(5000)` to the `fetch` call itself so the connection is released when the deadline passes.

The existing `onError` would turn that 504 into a 500, so the agent changes it to return `err.getResponse()` when `err instanceof HTTPException` and fall through to the old `Custom Error Message` otherwise. That keeps the behaviour of `/error` and `/type-error`, which throw plain errors, and lets the timeout's status and body reach the client. The `X-Response-Time` middleware still wraps the route, so a timed-out response carries the time it took to give up.

Tests go in `src/index.test.ts`, which already calls `app.request('http://localhost/')` under Vitest with `globals: true` from `vitest.config.ts`. The agent adds a test that stubs `fetch` with `vi.stubGlobal` to a promise that never settles, uses `vi.useFakeTimers()` and `vi.advanceTimersByTimeAsync(5000)`, and asserts `/fetch-url` answers 504 with `Gateway Timeout`; a second test stubs a fast `fetch` and asserts the route still answers 200 with the upstream status in the body; a third asserts `/error` still answers 500 with `Custom Error Message`. It runs `npm install` at the root and `npm -w basic test`, then `npx tsc --noEmit -p basic` against `basic/tsconfig.json`, and includes the output.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add request timeouts to this Hono app. Read package.json, wrangler.toml, vitest.config.ts, src/index.ts and src/index.test.ts first. Use Hono's timeout middleware from hono/timeout on the routes that wait on upstream calls (the /fetch-url route that fetches example.com), with a 5 second limit, and pass an AbortSignal.timeout to that fetch so the upstream request is cancelled too. Raise the hono dependency range to the first version that ships the timeout middleware if it is lower. Change app.onError so an HTTPException returns its own response and other errors keep the current 500 body. Add Vitest tests: a stalled fetch under fake timers gets 504 Gateway Timeout, a fast fetch still gets 200, and /error still gets the custom 500. Run the workspace's test script and a TypeScript check and include the output. Open a pull request.",
  "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 changes `basic/package.json` (the `hono` range), `basic/src/index.ts` (the `timeout` import and middleware, the `AbortSignal` on the fetch, and the `onError` branch for `HTTPException`) and `basic/src/index.test.ts` (three new tests). `wrangler.toml`, the other middleware and every other route are as they were.

The description lists the routes that now have a deadline and the one that still has none, quotes the Vitest summary and the `tsc` result, and explains why `onError` had to change. The full command output is in the transcript at `GET /o/{org}/sessions/{id}/messages`.

Before merging, a reviewer decides whether 5 seconds is right for that upstream, whether other routes should get a global `app.use('*', timeout(...))`, and whether the 504 body should be JSON for API clients. A follow-up message to the same session can make either change.

## Run it on every route that calls a third-party API

A team that adds outbound calls over time can send `POST /o/{org}/sessions` with this prompt each time a pull request introduces a new `fetch` to an upstream, naming the route in `input` and the repository in `resources`. Each run reads the app's own middleware and error handler, so a Hono app that already returns `HTTPException` responses gets only the timeout and the tests.

Send a `request_id` that is a UUID v5 of the route path so a retried request returns the run already started. A `webhook_url` on the API key delivers `run.completed` with the `session_url` to read the pull request from.

## Why run it on Rush?

A missing timeout is invisible until the upstream stalls in production, and the fix touches three places that are easy to get half right: the middleware, the fetch that keeps running after it, and the error handler that swallows the 504. The agent makes all three changes together in a sandbox, with fake timers proving the deadline fires, and keeps the commands and their output.

The pull request carries the tests and the passing summary, so a reviewer checks the limit and the routes rather than reproducing a hung upstream. Several Hono services can be done at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Does the timeout middleware cancel the upstream fetch?

No. It rejects the handler's promise and answers 504, but a `fetch` already in flight keeps running until it finishes or the runtime drops it. That is why the agent also passes `AbortSignal.timeout(5000)` to the fetch on `/fetch-url`, so the connection is closed at the same deadline.

### Why 504 and not 408?

408 means the client was slow to send its request; 504 means the server gave up waiting on something behind it, which is what happens here. Hono's middleware defaults to 504 with `Gateway Timeout`, and the second argument to `timeout()` takes a custom `HTTPException` if you want a different status or body.

### Why did the error handler have to change?

The app's `onError` returned a fixed 500 for every error, including the `HTTPException` the timeout throws, so clients would have seen 500 instead of 504. The agent returns `err.getResponse()` for `HTTPException` only, so the custom 500 still covers `/error` and `/type-error`.

### Will it apply to every route?

Only to the paths you mount it on. The agent limits it to `/fetch-url`, the one route that waits on the network; `app.use('*', timeout(...))` would cover everything, including `/etag/*` and `/auth/*`, and the FAQ in the pull request says how to add that if you want a global ceiling.

## More Hono jobs

- [Add a Typed RPC Client to a Hono API](https://getrush.ai/run/add-rpc-client/hono/)
- [Add Security Headers to a Hono App](https://getrush.ai/run/add-security-headers/hono/)
- [Add Streaming Responses to a Hono API](https://getrush.ai/run/add-streaming-responses/hono/)

## The same job on other stacks

- [Add Request Timeouts to a Koa App](https://getrush.ai/run/add-request-timeouts/koa/)
- [Add Connection Timeouts to a Tokio Server](https://getrush.ai/run/add-request-timeouts/tokio/)
- [Add Request Timeouts to an Actix Web App](https://getrush.ai/run/add-request-timeouts/actix/)

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