# Add Graceful Shutdown to a React Router App

Yes. An agent makes the Express server behind your React Router app drain requests on SIGTERM, fixes the Dockerfile so the signal reaches Node, and opens a PR.

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

## What the agent does

The agent first reads how the server starts and stops today. In a project made from the `node-custom-server` template in remix-run/react-router-templates, `server.js` creates an Express 5 app, mounts either Vite's middleware (development) or the built `build/server/index.js` handler (production), and ends with `app.listen(PORT, ...)` that logs the URL. Nothing holds the returned `http.Server`, nothing listens for `SIGTERM` or `SIGINT`, and in development the Vite server created with `createServer` in middleware mode is never closed. The `Dockerfile` builds on `node:24-alpine` in four stages and finishes with `CMD ["npm", "run", "start"]`, where `start` is `node server.js`, so inside a container the process that receives the stop signal is npm, not the Node server.

From that the agent changes `server.js` in three places. It keeps the `http.Server` that `app.listen` returns, registers one handler for `SIGTERM` and `SIGINT` that logs the signal, calls `server.close()` so no new connections are accepted and idle keep-alive connections are released, and then waits for in-flight requests to finish before exiting with code 0. A hard deadline read from `SHUTDOWN_TIMEOUT_MS`, started with `setTimeout(...).unref()`, calls `server.closeAllConnections()` and exits non-zero if a request is still running when the deadline passes, so a stuck handler cannot keep the old container alive forever. In the development branch the same handler also awaits `viteDevServer.close()`, so file watchers go away with the process.

The second change is the container. With npm as PID 1 the signal reaches npm rather than the server, so the agent changes the last line of the `Dockerfile` to run `node server.js` directly, and notes in the pull request that `docker run --init` or `tini` is the other half of the fix when the orchestrator cannot send signals to PID 1 any other way. A `shuttingDown` flag is exported so a health route, when the app has one, can answer `503` during the drain and a load balancer stops routing new traffic early.

Then it proves the behaviour in the sandbox. `npm run typecheck` runs `react-router typegen && tsc -b`, and `tsconfig.node.json` covers `server.js` with `checkJs`, so the new code is type-checked. `npm run build` and `npm run start` bring the production server up; the agent opens a keep-alive connection with `curl`, sends `SIGTERM` to the process with `kill`, and reads the log lines, the exit code, and the answer the in-flight request still received. A second run with a request that outlives `SHUTDOWN_TIMEOUT_MS` shows the forced close and the non-zero exit. Each command and its output is in the transcript.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add graceful shutdown to this React Router app. Read server.js, server/app.ts, package.json, tsconfig.node.json and the Dockerfile first. Keep the http.Server that app.listen returns, handle SIGTERM and SIGINT by calling server.close(), waiting for in-flight requests and exiting 0, with a hard deadline from SHUTDOWN_TIMEOUT_MS that calls closeAllConnections and exits non-zero. Close the Vite dev server too in the development branch, and export a shuttingDown flag a health route can read. Change the Dockerfile CMD to run node server.js directly so the signal reaches Node rather than npm, and explain --init in the pull request. Run npm run typecheck, npm run build and npm run start, then demonstrate with curl and kill that an in-flight request completes and the process exits 0, and that a request past the deadline is cut off with a non-zero exit. Open a pull request with the log 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 on its own branch with two changed files: `server.js`, with the signal handlers, the drain, the deadline and the exported flag, and the `Dockerfile`, whose last line now runs `node server.js`. The README gains a paragraph on `SHUTDOWN_TIMEOUT_MS` and on `--init`. Routes, the Vite config and `server/app.ts` are untouched.

The description pastes the two demonstrations: the log of a `SIGTERM` arriving while a request was open, the `200` that request still received, and the exit code; then the forced close after the deadline with its non-zero exit. The typecheck and build output sit in the transcript at `GET /o/{org}/sessions/{id}/messages` next to the commands.

Before merging, a reviewer checks that the deadline is shorter than the orchestrator's own kill timeout, since a drain longer than the grace period is just a slower crash, and that the health route, if the app has one, is wired to the exported flag. If the team keeps npm in the `CMD` for another reason, one follow-up message asks the agent to document the `--init` route instead.

## Run it on every service moved to rolling deploys

A developer switching a service to rolling deploys starts one run from the terminal with this prompt and the repository, and gets a pull request back while working on something else. The run's sandbox builds and starts the real server, so the demonstration in the description happened against this code and not a template.

For a fleet of services built from the same template, a script sends one `POST /o/{org}/sessions` per repository with the same body. Each run reads its own `server.js`, so a repository that already handles `SIGTERM` gets a pull request that only fixes the `CMD`, or none at all with a note saying why.

## Why run it on Rush?

Graceful shutdown is easy to write and hard to be sure of, because the failure only shows when a deploy cuts a request in half. The agent does not stop at reading the code: it starts the built server in its own sandbox, holds a request open, sends the signal and reads what the process did, including the forced close past the deadline. That second case is the one teams forget to test.

The transcript keeps those commands and their output, the typecheck of `server.js` under `checkJs`, and the build, so a reviewer sees the exit code rather than a promise. Several repositories can be handled at once, each in its own sandbox, and the sandbox parks when the turn ends so a follow-up picks up where it left off.

## Frequently asked questions

### Why change the Dockerfile CMD at all?

Because the template's `CMD ["npm", "run", "start"]` makes npm PID 1 inside the container, so the stop signal is delivered to npm and the Node server is not the process that receives it. Running `node server.js` directly puts the server at PID 1, and `--init` or `tini` handles the remaining PID 1 duties such as reaping.

### What happens to keep-alive connections that are idle?

`server.close()` stops accepting new connections and, on the Node the template's image uses, releases idle keep-alive connections on its own. Connections with a request in progress are left to finish, and only the deadline handler calls `closeAllConnections()` on whatever is still open.

### How long should SHUTDOWN_TIMEOUT_MS be?

Shorter than the grace period the orchestrator gives the container before it sends `SIGKILL`, and longer than the slowest request the app is expected to serve. The pull request sets a default and names both constraints, since the right value depends on the platform the team deploys to.

### Does this change anything in development?

Only that pressing Ctrl-C now closes the Vite dev server before the process exits, so file watchers do not linger. The routes, the Vite config and `server/app.ts` are not touched.

## More React Router jobs

- [Add a Health Check Route to a React Router App with a Custom Express Server](https://getrush.ai/run/add-health-checks/react-router/)
- [Add i18n to a React Router App](https://getrush.ai/run/add-i18n/react-router/)
- [Add a Custom 404 Page to a React Router App](https://getrush.ai/run/add-not-found-page/react-router/)

## The same job on other stacks

- [Add Graceful Shutdown to a Rust Axum Service](https://getrush.ai/run/add-graceful-shutdown/rust/)
- [Add Graceful Shutdown to an Express and Sequelize App](https://getrush.ai/run/add-graceful-shutdown/sequelize/)
- [Add Graceful Shutdown to a Socket.IO Server](https://getrush.ai/run/add-graceful-shutdown/socket-io/)

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