# Add Structured Logging to a React Router App With a Custom Express Server

Yes. An agent replaces morgan with pino in your React Router Express server, gives every request an id, hands the logger to loaders through context, and opens a PR.

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

## What the agent does

The agent reads how requests are logged today. In an app started from the `node-custom-server` template in remix-run/react-router-templates, `server.js` builds an Express 5 app with `compression`, disables `x-powered-by`, and branches on `NODE_ENV`: in development it mounts Vite's middleware and loads `./server/app.ts` through `ssrLoadModule` on every request, in production it serves `build/client/assets` as immutable for a year, calls `morgan("tiny")`, serves the rest of `build/client` for an hour and mounts the built app from `build/server/index.js`. So `morgan` logs only in production, prints one unstructured line per request, and development requests are not logged at all. Two `console.log` calls announce which server started, and the development branch's `catch` passes errors to `next(error)` with nothing logged. `server/app.ts` wraps `createRequestHandler` from `@react-router/express` with a `getLoadContext` that creates a `RouterContextProvider` and sets one value, `valueFromExpressContext` from `app/context.ts`, which `app/routes/home.tsx` reads in its loader. `package.json` pins `express` `^5.2.1`, `morgan` `^1.10.1`, `react-router` and `vite` `^8.0.3`, with `typecheck` running `react-router typegen && tsc -b`.

The change replaces `morgan` with `pino` and `pino-http`, in both branches. `server/logger.ts` creates the base logger with `level` from `LOG_LEVEL` defaulting to `info`, `redact` on `req.headers.authorization` and `req.headers.cookie`, and a `pino-pretty` transport only when `NODE_ENV` is `development`, so production emits one JSON object per line to stdout. `pino-http` is registered before the static handlers with `genReqId` that reuses an incoming `x-request-id` header when present and otherwise `crypto.randomUUID()`, and it sets the same id on the response header, so a client or a proxy can quote it. Each request then produces a single line with `req.id`, `req.method`, `req.url`, `res.statusCode` and `responseTime`, at `info` for success and `error` when the status is 500 or the handler threw. The two startup lines and the development branch's swallowed error become `logger.info` and `req.log.error` calls, and the static asset routes are logged at `debug` so the hourly asset traffic does not drown the route lines.

Loaders and actions get the same logger. `app/context.ts` gains `export const logger = createContext<Logger>()`, typed from `pino`, and `getLoadContext(req)` in `server/app.ts` sets it to `req.log`, the child logger `pino-http` attached with the request id. A loader then writes `context.get(logger).info({ route: "home" }, "loaded")` and the line carries the request's id without any threading of parameters, which is the point of putting it in context rather than importing a module-level logger into route files. `home.tsx` gets one such line so the pattern is visible, and `root.tsx`'s `ErrorBoundary` stays as the client-side rendering of errors; the server-side record of the same failure comes from the `pino-http` error line.

There is no test setup in the template, so the agent adds one that checks the only behaviour that matters here: the shape of a line. `server/logging.test.mjs`, run with `node --test`, starts the built server on a free port with `NODE_ENV=production`, requests `/` with an `x-request-id` header, and asserts that stdout contains a JSON line whose `req.id` equals the header, whose `res.statusCode` is 200, and which has no `authorization` field after a request that sent one. The agent runs `npm run typecheck`, `npm run build` and that test in its sandbox, and `npm run dev` once to confirm the pretty transport prints in development, and pastes the results and one sample JSON line into the pull request. `@types/morgan` and `morgan` leave `package.json`; `pino`, `pino-http` and `pino-pretty` enter it.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add structured logging to this React Router app's custom Express server. Read package.json, server.js, server/app.ts, app/context.ts, app/root.tsx, app/routes/home.tsx, react-router.config.ts, vite.config.ts and the Dockerfile first. Replace morgan with pino and pino-http in both the development and production branches of server.js: a base logger in server/logger.ts with the level from LOG_LEVEL, redaction of the authorization and cookie headers, and pino-pretty only when NODE_ENV is development; pino-http with a genReqId that reuses x-request-id or makes a UUID, echoed on the response; one line per request with id, method, url, status and response time, error level on 500 or a thrown error, debug level for static assets. Replace the console.log startup lines and log the error the development branch currently passes to next without logging. Add a logger context in app/context.ts set from req.log in getLoadContext, and use it in the home loader. Add server/logging.test.mjs for node --test that starts the built server, sends a request with x-request-id and an Authorization header, and asserts the JSON line's id, status and redaction. Remove morgan and its types. Run npm run typecheck, npm run build and the test, and open a pull request with the output and one sample log line.",
  "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

The pull request changes `server.js`, `server/app.ts`, `app/context.ts`, `app/routes/home.tsx` and `package.json`, adds `server/logger.ts` and `server/logging.test.mjs`, and removes `morgan` and `@types/morgan`. Its description pastes the `typecheck`, `build` and `node --test` output and one production log line, so a reviewer sees the exact fields a collector will receive before the change is deployed.

Every request now logs in both modes with the same id on the line and on the `x-request-id` response header, and a loader's own lines carry that id through context. The `Dockerfile` needs no change, since the server still writes to stdout and the container runtime collects it as before.

Before merging, a reviewer sets `LOG_LEVEL` in the deployment if the default is not wanted, confirms the redaction list covers any other secret header the app receives, and decides whether the asset lines should stay at `debug` or be dropped altogether.

## Run it on every service whose logs go to a collector

A team moving several Node services onto a log pipeline sends this body once per repository to `POST /o/{org}/sessions`, each with its own 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. Each run reads its own server: a service already on `pino` gets only the request id and the context wiring, one on Fastify gets its built-in `pino` configured instead of a new one, and one that deploys to a platform with its own request header uses that header's name in `genReqId`.

Each run opens its own pull request on its own branch, and the person who started the batch reads every sample log line from `GET /o/{org}/sessions`, newest first.

## Why run it on Rush?

The difficult part of structured logging in a React Router app is not the library but the plumbing: the logger has to exist in both the Vite development branch and the production branch, the request id has to reach the loaders without being passed by hand, and the one place errors were being dropped has to be found. The agent reads both branches, uses the `getLoadContext` seam the framework provides, and proves the line shape with a test that reads the server's real stdout.

The run keeps every command and its output, including the sample line, so review is about field names and levels rather than about whether the server still starts. Several services can be converted at once, each in its own sandbox, and each pull request carries its own sample line.

## Frequently asked questions

### Why pino rather than winston?

`pino-http` gives the per-request child logger with the id attached, which is what makes `req.log` in `getLoadContext` work with no extra code, and its JSON output is what most collectors parse without a custom format. In a service that already uses `winston` the agent keeps it and adds the request id and the context wiring to that logger instead.

### What happens to logs in development?

They appear now, which they did not before, since `morgan` was mounted only in the production branch. The `pino-pretty` transport renders them as readable lines when `NODE_ENV` is `development`, and the same code emits JSON in production, so there is one logging path with two renderers.

### How do loaders log with the request id?

Through the new `logger` entry in `app/context.ts`, set from `req.log` in `getLoadContext`. A loader calls `context.get(logger)` and gets the child logger `pino-http` created for that request, so every line it writes carries `req.id` without the loader knowing where the id came from.

### Are secrets kept out of the lines?

`pino-http` logs request headers by default, so `redact` lists `req.headers.authorization` and `req.headers.cookie`, and the test sends an `Authorization` header and asserts the line does not contain it. Any other header the app treats as secret is added to that list in the same place.

### Does this change the Docker image?

No. The image runs `npm run start`, which starts `server.js` in production mode, and the logger writes to stdout as `morgan` did. The only difference the runtime sees is that each line is a JSON object.

## More React Router jobs

- [Fix "'Switch' is not exported from 'react-router-dom'" after upgrading to React Router 6](https://getrush.ai/run/fix-switch-is-not-exported-from-react-router-dom/react-router/)
- [Turn a Labeled GitHub Issue Into a Pull Request on a React Router App](https://getrush.ai/run/github-issue-to-pr/react-router/)
- [Review Pull Requests on a React Router App](https://getrush.ai/run/review-pull-requests/react-router/)

## The same job on other stacks

- [Add Structured Logging to a Rocket API](https://getrush.ai/run/add-structured-logging/rocket/)
- [Add Structured Logging to a Sequelize App](https://getrush.ai/run/add-structured-logging/sequelize/)
- [Add Structured Logging to a Serverless Framework API from a Linear Issue](https://getrush.ai/run/add-structured-logging/serverless/)

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