# Add a Health Check Endpoint to a Cloudflare Worker

Yes. An agent adds a /health route to your Cloudflare Worker that checks its D1 binding, writes vitest tests in the Workers runtime for it, and opens a PR.

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

## What the agent does

The agent reads the Worker and its configuration before adding a route. In a project like the `d1-template` in cloudflare/templates, `wrangler.json` binds one D1 database as `DB` (`d1-template-database`), sets `compatibility_date` to `2025-10-08`, uploads source maps and enables observability. `src/index.ts` has a single `fetch` handler that runs `SELECT * FROM comments LIMIT 3` on every path and renders the rows into HTML through `renderHtml.ts`; there is no routing at all. `migrations/0001_create_comments_table.sql` creates the `comments` table and inserts three rows, and `package.json` applies it with `wrangler d1 migrations apply DB --local` before `wrangler dev` and `--remote` before `deploy`. The `check` script is `tsc && wrangler deploy --dry-run`, and there is no test file, while the repository's `AGENTS.md` asks every template for at least five tests written with `@cloudflare/vitest-pool-workers` and a `package-lock.json` regenerated from the root.

From that the agent adds routing by `URL.pathname` and keeps the HTML page as the default. `GET /health` and `HEAD /health` answer JSON with an overall status and one entry per check: a `SELECT 1` through the `DB` binding for connectivity, a `SELECT count(*) FROM comments` to show the migration has been applied, and the measured latency of each. Any thrown error turns the entry into a failure and the response into `503`, and every answer carries `Cache-Control: no-store` so a monitor never reads a cached result. The code lives in `src/health.ts` so `index.ts` stays short, and `renderHtml.ts` is untouched.

The tests follow the sibling `d1-starter-sessions-api-template` in the same repository, which has a `vitest.config.mts` using the `cloudflareTest` plugin pointed at the Wrangler config and a `test/index.spec.ts` that imports `env`, `createExecutionContext` and `waitOnExecutionContext` from `cloudflare:test`. The agent adds the same setup to `d1-template`, applies the SQL in `migrations/` to the test database with the `applyD1Migrations` helper `cloudflare:test` exports, and writes five cases: `200` with both checks passing, `503` after the `comments` table is dropped, `HEAD` with no body, the `no-store` header, and the HTML page still served at `/`.

Then it runs what the repository runs: `pnpm test` in the template, `pnpm run check` at the root, which lints every template with the `templates` CLI, checks Prettier and runs each template's `check`, and `pnpm run fix:lockfiles` so the template's `package-lock.json` matches the new dev dependencies. The README gets the endpoint under its existing headings, between the dashboard markers `AGENTS.md` requires, with a line on pointing a Cloudflare Health Check or any uptime monitor at `/health`.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add a health check endpoint to this Cloudflare Worker. Read wrangler.json, src/index.ts, src/renderHtml.ts, migrations/, package.json, README.md and the repository's AGENTS.md first, and use the d1-starter-sessions-api-template in this repository as the model for tests. Route by pathname and keep the existing HTML page at every other path. Answer GET and HEAD /health with JSON holding an overall status and one entry per check with its latency: SELECT 1 through the DB binding and SELECT count(*) FROM comments to show the migration applied; return 503 when a check throws and send Cache-Control: no-store always. Put the logic in src/health.ts. Add a vitest config with the cloudflareTest plugin, apply the migrations to the test database with applyD1Migrations from cloudflare:test, and write at least five tests covering the passing case, a 503 after dropping the table, HEAD, the no-store header and the HTML page. Run pnpm test here, pnpm run check and pnpm run fix:lockfiles at the root, document /health in the README between the dashboard markers, and 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 on its own branch with `src/health.ts`, the routing change in `src/index.ts`, `vitest.config.mts`, `test/health.spec.ts`, the new dev dependencies and `test` script in `package.json`, the regenerated `package-lock.json`, and the README paragraph. `renderHtml.ts`, `wrangler.json` and the migration are unchanged.

The description pastes the JSON the endpoint returns in the passing and failing cases, the vitest summary with the five tests, and the root `pnpm run check` result, which covers the template linter, Prettier and the `tsc && wrangler deploy --dry-run` check. The transcript at `GET /o/{org}/sessions/{id}/messages` keeps each command and its output.

Before merging, a reviewer checks that the `count(*)` query is cheap enough to run at the monitor's interval on the real table, that the endpoint exposes nothing beyond status and latency, and that the monitor they use treats `503` as down. One follow-up message to the same session adds a check for another binding, such as KV or R2, in the same shape.

## Run it on every Worker added to an uptime monitor

A developer about to point a monitor at a Worker starts one run from the terminal with this prompt and the repository, and gets a pull request with the endpoint and the tests while doing something else. The sandbox runs the tests in the Workers runtime through the vitest pool, so the D1 queries in the tests hit a real local database.

A platform team can send one `POST /o/{org}/sessions` per Worker repository; `GET /o/{org}/github` lists the ones the Rush GitHub App installation reaches. Each run reads that Worker's own bindings, so a Worker with KV and a queue gets checks for those instead of a D1 query.

## Why run it on Rush?

A health check that only returns `ok` is worse than none, because it hides a missing migration or a broken binding behind a green light. The agent reads `wrangler.json` to learn what the Worker depends on and writes a check per binding, then proves the failure path by dropping the table inside a test rather than asserting the happy case alone.

The proof travels with the pull request: the test output from the Workers runtime, the root `pnpm run check`, and the endpoint's actual JSON are in the transcript beside the commands that produced them. Several Workers can be handled at once, each in its own sandbox.

## Frequently asked questions

### Why query the comments table and not just SELECT 1?

`SELECT 1` proves the binding answers; `SELECT count(*) FROM comments` proves the migration in `migrations/` has been applied to the database the Worker is bound to. A fresh database with no tables passes the first and fails the second, which is exactly the deployment mistake the `predeploy` script exists to prevent.

### How do the tests get a database with the schema?

The vitest config uses the `cloudflareTest` plugin pointed at `wrangler.json`, so the `DB` binding exists inside the tests, and a setup step applies the SQL files from `migrations/` with the `applyD1Migrations` helper `cloudflare:test` exports. The failing-case test then drops the table and expects `503`.

### Does the endpoint change the existing page?

No. Every path other than `/health` still runs the same `SELECT * FROM comments LIMIT 3` and renders through `renderHtml.ts`, and one of the five tests asserts that. Only `src/index.ts` learns to look at the pathname.

### What should the monitor be?

Anything that fetches `/health` on an interval and alerts on a non-2xx answer, including Cloudflare's own Health Checks. The response sends `Cache-Control: no-store` so neither a browser nor an intermediate cache can hand the monitor a stale success.

## More Cloudflare Workers jobs

- [Validate Request Bodies in a Cloudflare Worker](https://getrush.ai/run/add-input-validation/cloudflare-workers/)
- [Add KV Caching to a Cloudflare Worker](https://getrush.ai/run/add-kv-caching/cloudflare-workers/)
- [Add a Queue Consumer to a Cloudflare Worker](https://getrush.ai/run/add-queue-consumer/cloudflare-workers/)

## The same job on other stacks

- [Add a Health Check Endpoint to a CodeIgniter 4 App](https://getrush.ai/run/add-health-checks/codeigniter/)
- [Add Health Checks to a Django REST Framework API](https://getrush.ai/run/add-health-checks/django-rest-framework/)
- [Add Health Checks to a Docker Compose Setup](https://getrush.ai/run/add-health-checks/docker-compose/)

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