> [Agent navigation index](/llms.txt)

# Server middleware and logging

Add application middleware and state, expose safe errors, and emit bounded structured logs while Brix preserves infrastructure ordering.

Add these integrations one at a time to an assembled server. A useful completion test sends one
successful and one failing harness request, checks the public error body and request ID, and observes
the expected lifecycle record without exposing credentials or exception details.

## Add middleware and render data

Global business middleware belongs in `defineBrixServer`; route-specific concerns belong on the
route's `middleware` option. Global middleware runs in array order after locale resolution and before
any route, including route authentication. Requests answered earlier, such as built-in assets and
cross-origin rejections, never reach it; see the [request order](/docs/server.md#what-happens-on-every-request). It receives
the typed `c.env`, `c.logger`, and `c.timings`.

Extend default serialized render data rather than replacing it. Here,
`businessContextMiddleware` is an application-owned Hono middleware. The example shares a
non-sensitive application label with islands:

```ts
export const brixServer = defineBrixServer(brix, {
  env,
  middleware: [businessContextMiddleware],
  renderData: (_c, defaults) => ({
    ...defaults,
    applicationName: "Booking",
  }),
});

```

The defaults are `baseUrl` (request origin), `urlPath`, `initialQueryParams`, `locale`, `nonce`,
`isProduction`, and `version`. The nonce exists only during SSR; Brix never serializes it into page
or fragment HTML, and browser renders observe an empty `nonce`. Custom render data is shared across
SSR and hydration for page and fragment scopes and is browser-visible; never include credentials.
Only this render data is serialized, not arbitrary server request data.

Do not put rendered HTML behind application response-cache middleware while Brix emits its default
request nonce: a cached body would retain its producer nonce while a later request receives a new CSP.
Use the manifest-driven edge admission flow instead and
[let the edge own CSP](/docs/server-auth-security.md#let-an-edge-own-csp-for-cached-html). API response
caching has no HTML nonce coupling.

Islands read this data with `useRenderData` from `brix/hooks`, without a store or custom context bridge. Define a shared browser-safe type extending `BaseRenderData`, annotate the callback's return type with it, and use the same type in `useRenderData<AppRenderData>()`. The generic is a compile-time description, not runtime validation. Render data is distinct from Hono request context and mutable stores. Keep authorization on the server; browser-visible identity fields are display data. Browser-safe is not public-cache-safe, so personalized fields require partitioned or disabled page and fragment caches. See [reading shared render data](/docs/islands.md#read-shared-render-data) for the island and isolated-test setup.

The default render-data version is the request's resolved `service.version`, or `"1"` when service metadata is absent. It is independent of the package version captured for the OpenAPI document and `X-App-Version` response header.

Locale resolution runs before global business middleware and route authentication. It cannot read
identity established by those later callbacks; render data runs later but cannot override the finalized
locale. For session-selected locales, share a request-memoized session lookup between `resolveLocale`
and auth rather than loading twice or reordering middleware. See
[session-backed locale resolution](/docs/translations-setup.md#resolve-locale-consistently).

## Handle errors without leaking details

Every default error body is JSON with a single `error` string:

- Unmatched routes return 404 `{ "error": "Not Found" }`.
- Unexpected exceptions return 500 `{ "error": "Internal Server Error" }`.
- Framework input failures return 400 or 415 with their message, such as
  `Invalid query parameters: ...` or `Invalid request body: ...` followed by the validation issue.
  When input makes a schema transform throw, the 400 says only `Invalid query parameters` or
  `Invalid request body`; the thrown error is its `cause`, not part of the response.
- Request schemas must be synchronous. An async refinement or transform cannot reject one input; it
  fails every request with an unexpected server error that names the schema problem.
- A deliberate `HTTPException` without its own `res` returns `{ "error": message }` with its status;
  one constructed with `res` returns that response.
- The cross-origin guard's 403 and the body limit's 413 are returned directly. They never reach
  `onError`.

Customize this only when the application needs another public contract. This example keeps the
default behavior for deliberate exceptions and reports unexpected ones through an
application-owned `telemetry` adapter:

```ts
import { BRIX_REQUEST_ID, defineBrixServer } from "brix/server";
import { HTTPException } from "brix/hono/http-exception";

export const brixServer = defineBrixServer(brix, {
  env,
  notFound: (c) => c.json({ error: "Not found" }, 404),
  onError: (error, c) => {
    if (error instanceof HTTPException) {
      if (error.res) return c.newResponse(error.res.body, error.res);
      return c.json({ error: error.message || "Request failed" }, error.status);
    }
    telemetry.capture(error, c.get(BRIX_REQUEST_ID));
    return c.json({ error: "Request failed" }, 500);
  },
});

```

A custom `onError` replaces the default policy. It receives unexpected API handler and
response-validation failures with their original cause, and also the framework's 400/415 and your
deliberate `HTTPException` values; preserve those explicitly, as above, so their status, body, and
headers pass through. `c.newResponse` keeps headers Brix prepared for the request; Brix also restores
its missing request ID and `Content-Language` on a raw `Response` returned from `onError`,
middleware, auth policies, or page loaders, without replacing values that response already sets. Do not serialize stack traces, provider responses, environment values, or
arbitrary error messages. Environment initialization failure happens before environment-dependent
application hooks: Brix returns a sanitized 500 and deliberately bypasses custom `onError`.

That early 500 still carries the safe request ID and configured static security policy. Brix does
not run application middleware, logging factories, dynamic asset-prefix or CSP callbacks, or
integration security hooks against unresolved environment values. See the
[failure-response security policy](/docs/server-auth-security.md#failure-responses) for the static
fallback, opt-outs, and OpenAPI path scoping.

## Attribute external dependency time

Every request has an explicit `c.timings` scope. Prefer passing it to native API and Contentful
clients, created once per request through `brixServer.createService` in a `"use server"` module. Here `SEARCH_URL` is a key from your environment schema:

```ts
"use server";

import { createApiClient } from "brix/contracts";
import { brixServer } from "#brix/server";

export const getSearchClient = brixServer.createService((c) =>
  createApiClient({ baseUrl: c.env.SEARCH_URL, timings: c.timings, dependency: "search" }),
);

```

Call `getSearchClient(c)` from handlers and public or authenticated page loaders; the factory runs
once per request and receives the request context without `render`. Services neither grant
rendering capability nor imply authentication, and client memoization does not cache response data.
Never put one request's timings on a shared module-level client; reuse lower-level connection pools
instead. See the [client definition](/docs/api-routes-clients.md#create-a-reusable-api-client) and
[page-loader example](/docs/pages.md#load-remote-data).

Measure any other async dependency directly:

```ts
const result = await c.timings.measure("search-index", () => searchIndex.query(input));

```

`measure` accepts a callback returning `PromiseLike<T>` and returns `Promise<T>`. A synchronous throw
while invoking the callback remains synchronous, and rejected promises are recorded too. Do not wrap
native client calls again. There is no async-local implicit scope.

Lifecycle logs include `timings.totalMs`, unioned `externalMs`, `unattributedMs`, and per-name
`dependencies` with duration and attempt count. Overlapping spans count once in external totals, so
these fields attribute wall time and are not CPU execution measurements. Tracking retains at most
1,000 spans and 100 distinct dependency names, each truncated to 100 characters; summaries can
therefore be partial. A dependency's `truncated` count reports its discarded spans, while summary
`truncated` reports every discarded span, including spans rejected after the distinct-name limit.
Native API attempts include response-body consumption; cache hits exclude upstream HTTP spans. Retry
backoff and schema validation are excluded. Streaming responses measure only through headers, not
body-stream lifetime. Remote cache I/O has separate `cache.dynamodb` or `cache.fastly` spans.

Timings do not report whether returned data was fresh or a cache fallback. A successful stale fallback
is an ordinary successful Result, and hooks report success even if an origin attempt failed. Use the
cache coordinator's bounded `onEvent` outcomes for aggregate fallback diagnostics; they do not carry
per-hook identity. Native Contentful errors expose `kind` for handled transport failures. Log selected
kind/status fields and the request ID rather than complete errors or provider payloads.

## Log requests safely

### Request IDs

Every response carries an `x-request-id` header, and handlers read the same value with
`c.get(BRIX_REQUEST_ID)` (the string `"brixRequestId"`) from `brix/server`. An incoming
`x-request-id` is reused when it is 1–128 characters of ASCII letters, digits, `.`, `_`, `:`, or
`-`; anything else is replaced by a random UUID (`crypto.randomUUID()`). Propagate the header from a
trusted proxy or load balancer to correlate its logs with Brix's.

A custom `logging.requestId(c)` resolver runs after environment initialization, may read `c.env`,
and takes precedence over the header. Its value must match the same format; if it returns
`undefined`, the incoming header is used, and an invalid value or a throw produces a random UUID. On
an environment initialization failure the resolver is not called.

### Configure logging

Runtime snapshot loading validates the snapshot format, not the application's Varlock schema again;
produce deployment snapshots through the [environment workflow](/docs/environment.md). In this example
`VERSION`, `STAGE`, `REGION`, and `TELEMETRY_ENDPOINT` are keys from your environment schema, and
`createTelemetrySink` is an application-owned `BrixLogSink` factory:

`src/brix.server.ts`

```ts
export const brixServer = defineBrixServer(brix, {
  env,
  service: (c) => ({
    name: "booking",
    version: c.env.VERSION,
    environment: c.env.STAGE,
  }),
  logging: {
    level: "info",
    flushTimeoutMs: 1_000,
    fields: (c) => ({ region: c.env.REGION }),
    sink: (c) => createTelemetrySink(c.env.TELEMETRY_ENDPOINT),
  },
});

```

Call `c.logger.debug/info/warn/error(message, fields?)` in handlers or middleware.
`c.logger.setFields(fields)` enriches later records for that request. Brix also writes lifecycle
records: `request.start`, then `request.end`, or `request.error` (at `error` level) when an exception
reached the error policy. Every record has `level`, `message`, `timestamp`, `requestId`, `method`,
`path` (pathname only), a valid incoming W3C `traceparent` (malformed values are omitted; for a
future version, only its 55-character version, trace ID, parent ID, and flags are kept), `service`
metadata, and application `fields`; lifecycle end records add `status`, `durationMs`, and the
dependency `timings` summary.

Application fields stay nested under `fields`, and keys that collide with the top-level names above
are dropped. Values are normalized to bounded JSON: at most 100 field keys per record, 100 entries
per nested object or array, and six levels of nesting. Getters become `"[Getter]"`, cycles
`"[Circular]"`, and `Error` values keep their name, message, stack, and cause.

Automatic error events omit exception messages, stacks, and causes. To export exception details,
explicitly log approved fields from `onError`; passing `{ error }` includes those details and requires
application redaction. Service metadata copies only string `name`, `version`, and optional
`environment`, each capped at 256 characters. Invalid metadata is omitted; getters are not invoked.

The scope starts after successful environment initialization and closes when middleware finishes
producing the response, not when a streamed body finishes. `durationMs` and `timings.totalMs` exclude
environment initialization and subsequent sink flushing; they are not end-to-end delivery latency.
Later logs are ignored and later dependency operations run without measurement. Pending spans are
clipped at closure. If a shared-load initiator ends before its joiners, its summary does not extend to
cover the remaining work or transfer that work to another request's scope.

### Delivery and flushing

Without a `sink`, Brix chooses console output for where the application runs:

- **Production builds:** newline JSON, one record per line, at `info` and above.
- **`brix dev`:** one readable line per finished request, at `info` and above.
- **Tests:** readable lines at `warn` and above.

Production JSON goes through the matching `console` method, so platform log pipelines such as
CloudWatch or Datadog receive every record. In development, Brix skips `request.start` and prints
each finished request as one colored line:

```text
14:02:31 GET     200  384ms  /products/42  · contentful 311ms ×2, pricing 22ms
14:02:31 WARN    cart nearly full  items=48  · POST /api/cart
14:02:32 GET     401    3ms  /api/me  · Sign in required
14:02:33 POST    500  1.83s  /api/checkout  · requestId=9f3c1a2b-…
    Error: Payment provider timed out
      at checkout (src/routes/api/checkout.ts:18:11)
    Caused by: Error: ETIMEDOUT

```

Only development output includes exceptions: server failures show the error, its causes, and
application stack frames (dependency frames are hidden), and intentional client errors such as
`HTTPException(401)` show their message inline. Exceptions never enter `BrixLogRecord`, so custom
sinks and JSON output never receive them. The test default hides request lines but keeps warnings
and errors; a custom sink keeps the `info` default in tests.

Set `logging.format` to `"json"` or `"pretty"` to choose the console format explicitly. The
`BRIX_LOG_FORMAT` and `BRIX_LOG_LEVEL` process variables override the environment defaults, but not
explicit `format` or `level` options. For example, `BRIX_LOG_LEVEL=warn brix dev` hides request
lines, `BRIX_LOG_LEVEL=debug brix dev` shows `c.logger.debug` records, and
`BRIX_LOG_FORMAT=json brix dev` previews production records. Invalid values are ignored with one
console warning. Colors follow `NO_COLOR`, `FORCE_COLOR`, and whether stdout is a terminal.
Readable output escapes control characters in paths, messages, fields, exceptions, and timing
names, so request or application text cannot forge log lines or send terminal escape sequences.

Configure a `BrixLogSink` (`write(record)` and optional `flush()`, either may be async), or
a request factory as above when the sink depends on initialized environment values. Set
`logging: false` to disable delivery.

Writes are ordered, and each request queues at most 1,000 records. **The response is returned only
after queued writes and `flush()` finish, or after `flushTimeoutMs` (default `1_000`) elapses.** A
slow sink therefore adds up to that much latency to every request; keep `write` fast, buffer
network export in the sink, and lower the timeout if latency matters more than completeness.
Timing out stops waiting and drops queued work, but does not cancel a write or flush already in
progress. Sink write failures, flush failures, queue overflow, and flush timeout each emit one
constant, detail-free console diagnostic per category per request.

Brix does not automatically collect secrets, environment values, users, cookies, query strings,
bodies, or arbitrary headers. Add fields deliberately and redact dynamic paths, errors, and
application fields in the sink before export. If the sink or fields factory throws, Brix disables
delivery for that request rather than falling back to the console, and writes one constant console
diagnostic the first time it happens in each application. If environment initialization fails, Brix
does not invoke environment-dependent factories or the request-ID resolver; unless `logging` is
`false`, it writes the `request.error` record to the console without failure details. That record
has the constant fields `{ "failure": "environment", "stage": ... }`, where `stage` is `runtime`
(no environment runtime is installed), `load` (the platform snapshot or secret provider failed), or
`parse` (the snapshot is invalid). Search for `failure: environment` to tell a misconfigured
deployment from application errors.

Once request behavior is covered, choose the production adapter in [deployment](/docs/deployment.md)
and repeat the request-ID and error checks against the deployed candidate.
