# Server-Sent Event Policies

> **Scope of this page**
>
> This page documents the Zuplo **gateway** runtime (API, AI, and MCP gateways), not the Developer Portal.
>
> It applies to every Zuplo hosting option: Managed Edge, Managed Dedicated, and Self-Hosted. See [Hosting options](https://zuplo.com/docs/articles/hosting-options).

Server-sent event (SSE) policies are functions that run on each event of a
`text/event-stream` response before the gateway sends it to the client. Use them
to redact fields, send each caller only their own events, or end a stream that
has run long enough, without writing an SSE parser in a custom handler.

Add SSE policies to a route with the `ssePolicies` option of the
[URL Forward](./url-forward.mdx) or [URL Rewrite](./url-rewrite.mdx) handler. To
use them with any other handler, call `applySsePolicies` from a custom outbound
policy. See
[Use SSE policies with any handler](#use-sse-policies-with-any-handler).

SSE policies work like the message policies of the
[WebSocket Pipeline Handler](./websocket-pipeline-handler.mdx), for a stream
that flows in one direction, from the backend to the client.

## How it works

With `ssePolicies` set, the handler reads the backend's response. If the
response is an event stream, the gateway parses each event and passes it through
your policies in order. The client receives the event the last policy returns.

| Backend sends                                              | What happens                                                                                             |
| ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| An event with data                                         | The policies run, and the client receives what they return                                               |
| A comment, such as `: keep-alive`                          | The client receives it unchanged, and no policy runs                                                     |
| An event without data, such as one with only `retry: 5000` | The client receives it, and no policy runs. The gateway removes any field the SSE format doesn't define. |
| A response that isn't `text/event-stream`                  | The client receives it unchanged                                                                         |

The policies run at any status code, so an error that the backend sends as an
event stream goes through them too. To leave errors alone, check `response.ok`
in your policy.

For example, a route that runs the `onlyMyEvents` and `redactEmail` policies
from [the examples below](#examples) gives caller `u_1` this stream:

| Backend sends                                                            | Client receives (caller `u_1`)                 |
| ------------------------------------------------------------------------ | ---------------------------------------------- |
| `data: {"userId":"u_1","email":"ada@example.com","text":"Build passed"}` | `data: {"userId":"u_1","text":"Build passed"}` |
| `data: {"userId":"u_2","text":"Deploy started"}`                         | Nothing                                        |
| `: keep-alive`                                                           | `: keep-alive`                                 |

## Configuration

Add an `ssePolicies` array to the handler's `options`. Each entry names a
function that one of your project's modules exports. Write `module` as
`$import(./modules/<module-name>)`.

```json title="config/routes.oas.json"
"/notifications": {
  "get": {
    "operationId": "notifications",
    "x-zuplo-route": {
      "corsPolicy": "none",
      "handler": {
        "export": "urlForwardHandler",
        "module": "$import(@zuplo/runtime)",
        "options": {
          "baseUrl": "https://api.example.com",
          "ssePolicies": [
            {
              "module": "$import(./modules/notification-events)",
              "export": "onlyMyEvents"
            },
            {
              "module": "$import(./modules/notification-events)",
              "export": "redactEmail"
            }
          ]
        }
      },
      "policies": {
        "inbound": ["api-key-inbound"]
      }
    }
  }
}
```

The URL Rewrite handler takes the same `ssePolicies` option next to
`rewritePattern`.

:::caution{title="Two different policies blocks"}

`ssePolicies` inside `handler.options` configures the functions that run on each
event. The route-level `policies` block configures the standard request policies
— such as [API Key Authentication](../policies/api-key-inbound.mdx) — that run
once, before the gateway calls the backend.

:::

If an entry names a function its module doesn't export, or its `module` isn't
written as `$import(...)`, the build fails with an error that names the entry.

## Write an SSE policy

An SSE policy is an exported function of type `ServerSentEventPolicy`:

```ts
import {
  ServerSentEvent,
  ServerSentEventClient,
  ZuploContext,
  ZuploRequest,
} from "@zuplo/runtime";

type ServerSentEventPolicy = (
  event: ServerSentEvent,
  client: ServerSentEventClient,
  response: Response,
  request: ZuploRequest,
  context: ZuploContext,
) => ServerSentEvent | undefined | Promise<ServerSentEvent | undefined>;
```

| Parameter  | Description                                                                                                                                                                   |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `event`    | The event from the backend, as the previous policy returned it. See [The event](#the-event).                                                                                  |
| `client`   | The client's connection. Call `client.send()` to send an extra event or `client.close()` to end the stream. See [The client](#the-client).                                    |
| `response` | The backend's response. Read its status and headers. Reading its body throws an error, because the gateway is already reading it.                                             |
| `request`  | The [`ZuploRequest`](../programmable-api/zuplo-request.mdx) that opened the stream. `request.user` holds the caller an authentication policy identified.                      |
| `context`  | The [`ZuploContext`](../programmable-api/zuplo-context.mdx) of the request. `context.custom` lasts as long as the stream, so use it to keep state from one event to the next. |

The return value controls what happens next:

- **Return the event**, changed or not, to pass it to the next policy. After the
  last policy, the client receives it.
- **Return `undefined`** to drop the event. No further policies run for it.

Policies can be `async`. If a policy throws an error, rejects, or returns
something other than an event or `undefined`, the gateway logs the error, drops
the event, and the stream continues.

### The event

`ServerSentEvent` holds the four fields the SSE format defines:

| Field   | Type     | Description                                                                                            |
| ------- | -------- | ------------------------------------------------------------------------------------------------------ |
| `data`  | `string` | The event's data. The gateway joins several `data:` lines with newlines.                               |
| `event` | `string` | Optional. The event type. Clients treat an event without one as a `message` event.                     |
| `id`    | `string` | Optional. The event ID. Clients send the last ID they received in `Last-Event-ID` when they reconnect. |
| `retry` | `number` | Optional. The reconnection time in milliseconds.                                                       |

To change an event, return a copy with the fields you change, such as
`{ ...event, data }`. Copying the event keeps its `id`, so clients that
reconnect still resume from the right place.

The gateway writes each event from these four fields. The `event` and `id`
fields can't contain a line break, and `retry` must be a whole number of
milliseconds; the gateway drops an event that breaks these rules and logs an
error.

### The client

`ServerSentEventClient` has two methods. Call them while the policy runs; after
the policy returns or its promise settles, they throw an error.

| Method        | Description                                                                                                                                                                                                                      |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `send(event)` | Sends an event to the client ahead of the event the policy returns. Pass a string to send it as the data of a `message` event, or a `ServerSentEvent` to set the other fields. Events sent this way skip the remaining policies. |
| `close()`     | Ends the stream after the events already sent, and stops reading from the backend. The gateway ignores the policy's return value, and no further policies run.                                                                   |

## Examples

Each example is a module in your project's `modules` folder, such as
`modules/notification-events.ts`. List the exports you want in the route's
`ssePolicies` option.

### Send each caller only their events

This policy compares the `userId` in each event with the caller that an
authentication policy, such as
[API Key Authentication](../policies/api-key-inbound.mdx), identified. Other
callers' events are dropped.

```ts title="modules/notification-events.ts"
import { ServerSentEventPolicy } from "@zuplo/runtime";

export const onlyMyEvents: ServerSentEventPolicy = (
  event,
  client,
  response,
  request,
) => {
  // Data that isn't JSON throws here, and the gateway drops the event
  const { userId } = JSON.parse(event.data);
  return userId === request.user?.sub ? event : undefined;
};
```

### Remove a field

This policy removes the `email` field from each event and keeps the other
fields, including `id`.

```ts title="modules/notification-events.ts"
import { ServerSentEventPolicy } from "@zuplo/runtime";

export const redactEmail: ServerSentEventPolicy = (event) => {
  const message = JSON.parse(event.data);
  delete message.email;
  return { ...event, data: JSON.stringify(message) };
};
```

### End the stream

This policy counts events in `context.custom`. After 500 events, it sends the
client a `limit` event and ends the stream. The gateway stops reading from the
backend.

```ts title="modules/notification-events.ts"
import { ServerSentEventPolicy } from "@zuplo/runtime";

const MAX_EVENTS = 500;

export const limitEvents: ServerSentEventPolicy = (
  event,
  client,
  response,
  request,
  context,
) => {
  context.custom.eventCount = (context.custom.eventCount ?? 0) + 1;
  if (context.custom.eventCount > MAX_EVENTS) {
    client.send({
      event: "limit",
      data: JSON.stringify({ message: "Event limit reached" }),
    });
    client.close();
    return undefined;
  }
  return event;
};
```

### Reuse logic from WebSocket message policies

A WebSocket and the SSE `client` both have `send()` and `close()`, so one module
can hold the logic for both kinds of route. This module removes the `ssn` field
and ends the connection after 500 messages:

```ts title="modules/shared.ts"
import { ZuploContext } from "@zuplo/runtime";

// A WebSocket and the SSE client both have these methods
interface Connection {
  send(data: string): void;
  close(): void;
}

// Removes the ssn field. Drops messages that aren't JSON.
export function redactSsn(text: string): string | undefined {
  let message: Record<string, unknown>;
  try {
    message = JSON.parse(text);
  } catch {
    return undefined;
  }
  delete message.ssn;
  return JSON.stringify(message);
}

// Tells the client and closes the connection after 500 messages
export function overLimit(connection: Connection, context: ZuploContext) {
  context.custom.messageCount = (context.custom.messageCount ?? 0) + 1;
  if (context.custom.messageCount <= 500) {
    return false;
  }
  connection.send(JSON.stringify({ message: "Limit reached" }));
  connection.close();
  return true;
}
```

The SSE policy and the WebSocket outbound message policy each call the shared
functions:

```ts title="modules/sse-policies.ts"
import { ServerSentEventPolicy } from "@zuplo/runtime";
import { overLimit, redactSsn } from "./shared";

export const sseOutbound: ServerSentEventPolicy = (
  event,
  client,
  response,
  request,
  context,
) => {
  if (overLimit(client, context)) {
    return undefined;
  }
  const data = redactSsn(event.data);
  return data === undefined ? undefined : { ...event, data };
};
```

```ts title="modules/websocket-policies.ts"
import { ZuploContext, ZuploRequest } from "@zuplo/runtime";
import { overLimit, redactSsn } from "./shared";

export async function webSocketOutbound(
  data: string,
  target: WebSocket,
  source: WebSocket,
  request: ZuploRequest,
  context: ZuploContext,
) {
  // In an outbound policy, `target` is the client
  if (overLimit(target, context)) {
    return undefined;
  }
  return redactSsn(data);
}
```

## Use SSE policies with any handler

To run SSE policies on a route that uses another handler, such as a
[Function Handler](./custom-handler.mdx), call `applySsePolicies` from a
[custom outbound policy](../policies/custom-code-outbound.mdx). Pass the policy
functions in the order they run.

```ts title="modules/sse-policies-outbound.ts"
import { applySsePolicies, ZuploContext, ZuploRequest } from "@zuplo/runtime";
import { onlyMyEvents, redactEmail } from "./notification-events";

export default async function (
  response: Response,
  request: ZuploRequest,
  context: ZuploContext,
) {
  return applySsePolicies(response, request, context, [
    onlyMyEvents,
    redactEmail,
  ]);
}
```

`applySsePolicies` returns a response that isn't an event stream unchanged. The
response it returns for an event stream keeps the status and headers, without
`Content-Length` or `Content-Encoding`, because the gateway rewrites the body.

## Compression

The gateway must decompress a stream to read its events. With `ssePolicies` set,
the handler sends `Accept-Encoding: gzip, br` to the backend in place of the
client's header.

If the backend still sends the stream with another content coding, such as
`deflate` or `zstd`, the gateway can't read it. The client receives a
`502 Bad Gateway` response, and the request log says which encoding the backend
used. `applySsePolicies` behaves the same way, but doesn't change the request to
the backend, so make sure the backend sends the stream uncompressed or
compressed with `gzip` or `br`.

## Limits

- The gateway drops an event larger than 10 MiB before the policies run, logs a
  warning, and the stream continues.
- MCP Gateway routes don't run SSE policies. Adding `ssePolicies` to one fails
  the build.

## Related documentation

- [URL Forward Handler](./url-forward.mdx)
- [URL Rewrite Handler](./url-rewrite.mdx)
- [WebSocket Pipeline Handler](./websocket-pipeline-handler.mdx) - message
  policies for WebSocket routes
- [Streaming responses and Server-Sent Events](../articles/streaming-responses-sse.mdx)
