# Add a Health Check Endpoint to a Node.js App

Yes. An agent adds a /healthz route that pings MongoDB, a Dockerfile HEALTHCHECK and a Compose service_healthy dependency, tests the route and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-health-checks/nodejs/). 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 how the app starts before it adds a route. In an app shaped like OWASP/NodeGoat, `server.js` opens the database with `MongoClient.connect(db, (err, db) => ...)` from the `mongodb` 2.x driver, exits the process when that fails, and only then builds the Express 4 app, wires `express-session`, the Swig view engine and `routes(app, db)` from `app/routes/index.js`. `config/env/all.js` reads `PORT` with a default of 4000 and `MONGODB_URI` with a default of `mongodb://localhost:27017/nodegoat`. There is no route that answers a load balancer: `app/routes/index.js` registers `/`, `/login`, `/signup`, `/dashboard`, `/profile`, `/contributions`, `/benefits` and the rest, all of them pages behind the session.

The container side has the same gap. `Dockerfile` builds on `node:12-alpine`, runs as the `node` user and exposes 4000 with no `HEALTHCHECK`. `docker-compose.yml` starts a `mongo:4.4` service and a `web` service whose `command` is a shell loop, `until nc -z -w 2 mongo 27017 ... && node artifacts/db-reset.js && npm start; do sleep 2; done`, which is a readiness check written by hand. `Procfile` runs `forever -m 5 server.js`, so a crash is restarted blindly rather than reported.

The agent adds `GET /healthz` in `app/routes/index.js`, outside the `isLoggedIn` middleware, that runs `db.command({ ping: 1 })` against the connected database and answers `200` with `{ status: "ok" }` or `503` with the error name, never the connection string. It adds `HEALTHCHECK` to the `Dockerfile` using `wget -qO- http://localhost:4000/healthz`, which the Alpine base image has, with an interval, timeout and start period. In `docker-compose.yml` it gives `mongo` a `healthcheck` that runs `mongo --eval "db.adminCommand('ping')"`, replaces the `nc` loop with `depends_on: mongo: condition: service_healthy` and keeps `node artifacts/db-reset.js && npm start` as the command. The obsolete `version: "3.7"` line goes, since Compose v2 warns on it.

For the test it follows the repository's own setup: `Gruntfile.js` already has a `mochaTest:unit` target for `test/unit/*.js` with no files in it, so the agent adds `test/unit/healthz-test.js` using `mocha`, `should` and the `needle` HTTP client the app already depends on, starting the app with `NODE_ENV=test` against a MongoDB it runs in the sandbox. It runs `grunt test`, `docker compose up --wait` to see both services turn healthy, and `jshint` as the `lint.yml` workflow does, then opens a pull request.

## 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 Node.js app. Add GET /healthz that pings the MongoDB connection and answers 200 when it responds and 503 when it does not, without exposing the connection string. Add a HEALTHCHECK to the Dockerfile that calls it, and in docker-compose.yml give the MongoDB service a healthcheck and make the web service depend on it with condition service_healthy instead of the shell loop. Write a mocha test for the route using the test runner the Gruntfile already defines, run the tests and the linter, bring the Compose stack up with --wait to show both services become healthy, 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. The diff adds the `/healthz` handler in `app/routes/index.js`, a `HEALTHCHECK` line in `Dockerfile`, a `healthcheck` on the `mongo` service and a `service_healthy` dependency on `web` in `docker-compose.yml`, and a new `test/unit/healthz-test.js`. The description shows a sample `200` and `503` body and explains why the route sits outside the session middleware.

The run's record keeps `grunt test` with the new unit test, the `jshint` run, and `docker compose up --wait` with the lines where `mongo` and then `web` report healthy. It also keeps `docker inspect` output for the `web` container showing the health status the new `HEALTHCHECK` produced.

Before merging, a reviewer checks that `/healthz` does not leak the database name or host in its error body, that the `HEALTHCHECK` start period is longer than the app's cold start with `db-reset`, and that the Procfile and any platform that runs the app without Docker also point their checks at the new path.

## Run it on every new service in the repository

In the console, an automation with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` starts one run per pull request that adds a server entry point or a Compose service, with the pull request as its context, in the Project that has the repository. The run checks for a health route and a container health check and comments with the missing pieces or pushes them to the branch, as the prompt says.

From your own server, the same work is one `POST /o/{org}/sessions` per repository, with the repository in `resources`. A webhook on the API key posts `run.completed` or `run.failed` when the turn finishes, with the `session_url` to read the pull request link and the Compose logs.

## Why run it on Rush?

A health check is only proven by watching an orchestrator act on it. The sandbox runs Docker, so the agent builds the image, brings the Compose stack up and reads the health transitions, which a laptop with a different Node or MongoDB version cannot stand in for. The logs stay with the run.

The change spans a route, a Dockerfile, a Compose file and a test, four files a reviewer wants to see together. One run produces one pull request with all four and the proof that the stack came up healthy, and a run per repository covers a fleet of services the same way.

## Frequently asked questions

### Why not just check that the process is up?

The process stays up while MongoDB is unreachable, and every real page would then fail. Pinging the database from the route makes the check mean what a load balancer wants it to mean. A separate liveness route that answers `200` without the ping can be added if the orchestrator needs both.

### Does the route need authentication?

No. It is registered before the `isLoggedIn` middleware and returns no user data. If the app is exposed to the internet, the reviewer can restrict it to the orchestrator's network in the proxy rather than in the app.

### Will this change the Node version or the old dependencies?

No. The agent writes the route against the `mongodb` 2.x driver and Express 4 the app already uses and keeps the `node:12-alpine` base. A deliberately outdated dependency set, as in a training app, is left for its own change.

### What about the forever restart loop in the Procfile?

It stays. A platform that reads the Procfile can be pointed at `/healthz` separately; the pull request describes that step but does not change the Procfile, since it has no health check field of its own.

## More Node.js jobs

- [Add Input Validation to a Node.js Express App](https://getrush.ai/run/add-input-validation/nodejs/)
- [Move Express Sessions from MemoryStore to MongoDB in a Node.js App](https://getrush.ai/run/add-mongo-session-store/nodejs/)
- [Set Up npm Trusted Publishing for a Node.js Package](https://getrush.ai/run/add-npm-trusted-publishing/nodejs/)

## The same job on other stacks

- [Add Health Checks to a Phoenix App](https://getrush.ai/run/add-health-checks/phoenix/)
- [Add Health Checks to a Phoenix LiveView App](https://getrush.ai/run/add-health-checks/phoenix-liveview/)
- [Add Health Checks to a Quarkus Service](https://getrush.ai/run/add-health-checks/quarkus/)

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