# Add Health Checks to an Express and Mongoose API

Yes. An agent adds /healthz and /readyz to your Express API, with readiness pinging MongoDB through the Mongoose connection, a Jest test and a Docker HEALTHCHECK.

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

## What the agent does

The agent starts with how the server connects, because a readiness check has to ask the same connection the handlers use. In an API like hagopj13/node-express-boilerplate, `src/index.js` calls `mongoose.connect` with the URL and options from `src/config/config.js` and only then starts `app.listen`, and it closes the server on `SIGTERM`; `src/app.js` installs helmet, JSON parsing, sanitising, compression, CORS and `passport` with the JWT strategy, mounts `src/routes/v1/index.js` at `/v1`, and turns any unknown path into a `404` `ApiError` before the error handlers. `routes/v1/index.js` mounts `/auth` and `/users` always and `/docs` only in development. `package.json` pins Mongoose 5 (5.13.20 in `yarn.lock`), Express 4, Jest 26 and supertest 6, with `test` running `jest -i`. There is no health route.

The agent then decides what each probe means. `GET /healthz` is liveness: Express is answering, so it returns `200` with `{"status": "ok"}` and touches nothing. `GET /readyz` is readiness: it reads `mongoose.connection.readyState`, and when that is `1` it runs `mongoose.connection.db.admin().ping()` with a two second timeout and answers `200` with `{"status": "ok", "mongodb": "ok"}`, or `503` naming the failing check. The agent writes both in `src/routes/v1/health.route.js` and adds them to `defaultRoutes` in `routes/v1/index.js`, so they live under `/v1` like everything else and never pass through `auth()`. It documents them with the same `@swagger` comments the other route files carry, so `/v1/docs` lists them.

Two existing pieces need a small change. `src/config/morgan.js` logs every successful request at `info`, and a probe every few seconds would fill the log, so the `skip` functions get a check for the two paths. The `Dockerfile` installs with `yarn install --pure-lockfile` and exposes 3000 but has no `HEALTHCHECK`, so the agent adds one that runs busybox `wget -qO- http://127.0.0.1:3000/v1/readyz` on an interval, which `node:alpine` ships where `curl` is absent. `docker-compose.yml` and its `mongo:4.2.1-bionic` service stay as they are.

The test is `tests/integration/health.test.js` and uses `setupTestDB` from `tests/utils/setupTestDB.js`, which connects Mongoose before all tests and disconnects after, with `supertest` against `src/app` as `docs.test.js` does: `/v1/healthz` is `200`; `/v1/readyz` is `200` with a connected database; after `mongoose.disconnect()` inside the test, `/v1/readyz` is `503` and `/v1/healthz` is still `200`. The sandbox has no Docker, so the agent installs it (`sudo apt-get install -y docker.io`, then starts `dockerd`) and runs the same `mongo:4.2.1-bionic` image `docker-compose.yml` names on port 27017, sets `MONGODB_URL` and `JWT_SECRET` as `.env.example` shows, and runs `yarn lint` and `yarn test` the way `.travis.yml` lists them, then starts the app and curls both routes.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add health check routes to this Express and Mongoose API. Read package.json, src/index.js, src/app.js, src/routes/v1/index.js, src/routes/v1/docs.route.js, src/config/config.js, src/config/morgan.js, src/middlewares/error.js, tests/utils/setupTestDB.js, tests/integration/docs.test.js, jest.config.js, Dockerfile, docker-compose.yml and .env.example first. Add GET /v1/healthz that returns JSON 200 without touching the database and GET /v1/readyz that checks mongoose.connection.readyState and pings MongoDB through the existing connection with a short timeout, returning 503 with the failing check named. Put them in a new route file registered in routes/v1/index.js, outside any auth middleware, with swagger comments like the other routes. Skip both paths in the morgan loggers. Add a HEALTHCHECK to the Dockerfile that calls /v1/readyz. Write an integration test using setupTestDB and supertest that covers both routes, including readiness after mongoose.disconnect. Start MongoDB in the sandbox, run yarn lint and yarn test, start the app and curl both routes, then open a pull request that shows the output.",
  "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 adds `src/routes/v1/health.route.js` and `tests/integration/health.test.js`, changes `src/routes/v1/index.js` by one entry in `defaultRoutes`, changes `src/config/morgan.js` by the two-path skip, and adds a `HEALTHCHECK` line to the `Dockerfile`. The description shows `curl -i` for both routes against a running server, the Jest output with the new test file's cases, and the timeout value in one place.

The run's record keeps the Docker install, the `mongo` container start, `yarn lint`, the full `yarn test` run and the two `curl` calls, so the proof that readiness flips to `503` when the connection drops is in the log and not only in the description.

Before merging, a reviewer decides whether readiness should also check the SMTP transport `config.js` configures, whether the orchestrator's probes should point at `/v1/readyz` or `/v1/healthz`, and whether the `HEALTHCHECK` interval suits the deployment. The agent changes no model, no controller and no existing route.

## Run it on every Node service without probes

A team with several Express services starts one run per repository from its own server: one `POST /o/{org}/sessions` each, with the repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started instead of opening a second pull request. Each run reads its own `src/index.js` and finds where that service keeps its connection.

To keep readiness meaningful afterwards, an automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "if this pull request adds a datastore, queue or outbound client the service cannot work without, add it to the readiness route and say so in a comment" reads each new pull request. The trigger adds the pull request after the prompt and fires only for owners, members and collaborators, never for a fork.

## Why run it on Rush?

A health route written without running the service is wrong in small ways that only show in production: mounted behind `auth()` so the probe gets `401`, logged by morgan on every tick, answering `200` while `readyState` is `0` because it never asked, or a `HEALTHCHECK` that calls `curl` in an image that has none. The agent runs the real app in its own sandbox with a real MongoDB, hits both routes, disconnects Mongoose in a test and watches the answer change, so the pull request carries behaviour and not intent.

Every command stays with the run, from the Docker install to the `curl` lines, and the pull request cites them. Doing the same for a dozen Node services at once costs no more attention than one, because each run has its own machine, its own record and its own pull request.

## Frequently asked questions

### Why two routes instead of one?

Because an orchestrator treats them differently. A failing liveness probe restarts the process, which does nothing for a MongoDB that is down and would restart a healthy server in a loop. A failing readiness probe only takes the instance out of rotation until the database is back. `/healthz` checks the process; `/readyz` checks what the process needs.

### Why check readyState and then ping?

`readyState` is free and answers at once when Mongoose knows it is disconnected, which is the common failure. The `admin().ping()` on the same connection catches the other case, a socket Mongoose still thinks is open to a server that has stopped answering, and the two second timeout keeps a hung server from hanging the probe.

### Do the routes appear in /v1/docs?

Yes. `docs.route.js` builds the OpenAPI document from `@swagger` comments in `src/routes/v1/*.js`, so the new route file carries the same comment blocks the user and auth routes do, and the two probes show up under a `Health` tag in development. In production `/v1/docs` is not mounted at all, as `docs.test.js` checks.

### Why wget in the HEALTHCHECK?

The image is `node:alpine`, which ships busybox and its `wget` but no `curl`, so the check uses what is already there and adds no package to the image. It runs inside the container, where `127.0.0.1:3000` is the server's own address, and exits non-zero on anything but a `200`.

## More Mongoose jobs

- [Add OpenTelemetry Tracing to an Express and Mongoose API](https://getrush.ai/run/add-opentelemetry/mongoose/)
- [Add Optimistic Locking to a Mongoose API](https://getrush.ai/run/add-optimistic-locking/mongoose/)
- [Add Request ID Logging to an Express and Mongoose API](https://getrush.ai/run/add-request-id-logging/mongoose/)

## The same job on other stacks

- [Add Health Checks to a NestJS API](https://getrush.ai/run/add-health-checks/nestjs/)
- [Add a Health Check Endpoint to a Node.js App](https://getrush.ai/run/add-health-checks/nodejs/)
- [Add Health Checks to a Phoenix App](https://getrush.ai/run/add-health-checks/phoenix/)

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