Handlers

Server-Sent Event Policies

Applies to
Gatewayruntime for API, AI, and MCP gateways
Hosting
Managed EdgeManaged DedicatedSelf-Hosted

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 or URL Rewrite handler. To use them with any other handler, call applySsePolicies from a custom outbound policy. See Use SSE policies with any handler.

SSE policies work like the message policies of the WebSocket Pipeline Handler, 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 sendsWhat happens
An event with dataThe policies run, and the client receives what they return
A comment, such as : keep-aliveThe client receives it unchanged, and no policy runs
An event without data, such as one with only retry: 5000The 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-streamThe 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 gives caller u_1 this stream:

Backend sendsClient 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>).

JSONconfig/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.

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 — 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:

TypeScriptCode
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>;
ParameterDescription
eventThe event from the backend, as the previous policy returned it. See The event.
clientThe client's connection. Call client.send() to send an extra event or client.close() to end the stream. See The client.
responseThe backend's response. Read its status and headers. Reading its body throws an error, because the gateway is already reading it.
requestThe ZuploRequest that opened the stream. request.user holds the caller an authentication policy identified.
contextThe ZuploContext 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:

FieldTypeDescription
datastringThe event's data. The gateway joins several data: lines with newlines.
eventstringOptional. The event type. Clients treat an event without one as a message event.
idstringOptional. The event ID. Clients send the last ID they received in Last-Event-ID when they reconnect.
retrynumberOptional. 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.

MethodDescription
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, identified. Other callers' events are dropped.

TypeScriptmodules/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.

TypeScriptmodules/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.

TypeScriptmodules/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:

TypeScriptmodules/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:

TypeScriptmodules/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 }; };
TypeScriptmodules/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, call applySsePolicies from a custom outbound policy. Pass the policy functions in the order they run.

TypeScriptmodules/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.
Last modified on