# Fastify

URL: https://tailrace.dev/docs/integrations/fastify

> OpenAI-compatible Fastify plugin - scan chat bodies and SSE streams, return 422 on policy block.



Enforce data policy on OpenAI-compatible chat routes in Fastify. Scan request messages before upstream, scan JSON and SSE responses on the way back.

## Quickstart [#quickstart]

```ts
import { createTailrace } from "@tailrace/core";
import { tailraceFastify } from "@tailrace/fastify";
import Fastify from "fastify";

const app = Fastify();
const tailrace = createTailrace();

await app.register(
  tailraceFastify(tailrace, {
    agent: (req) => String(req.headers["x-agent-id"] ?? "default"),
    workflowId: (req) => String(req.headers["x-workflow-id"] ?? "default"),
  }),
);
```

Peer: `fastify` `>=4`. Only `mode: "openai-compatible"` in v0.1. Uses `preHandler` + `onSend` / stream wrapping.

## Boundaries covered [#boundaries-covered]

| Location                | Tailrace boundary                                   | Direction            |
| ----------------------- | --------------------------------------------------- | -------------------- |
| Chat request messages   | `{ kind: "model", provider }` (`model` field as-is) | Outbound to upstream |
| JSON chat completion    | same model boundary                                 | Inbound              |
| SSE `text/event-stream` | same; carry-buffer across chunks                    | Inbound              |

Block → **422** `{ error: { type: "policy_violation", entity, rule } }`. SSE: cancel upstream, emit one error `data:` event, close (abort-only; no `streamBlockBehavior` in v0.1).

## Guides [#guides]

* [Block secrets in a Fastify app](/docs/guides/block-secrets-in-fastify)
* [Boundaries](/docs/concepts/boundaries)

## Reference [#reference]

* [Fastify package](/docs/reference/fastify)
* [HTTP shared pipeline](/docs/reference/http)
