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 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 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>).
config/routes.oas.json
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:
Code
| Parameter | Description |
|---|---|
event | The event from the backend, as the previous policy returned it. See 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. |
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 that opened the stream. request.user holds the caller an authentication policy identified. |
context | The 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
undefinedto 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, identified. Other
callers' events are dropped.
modules/notification-events.ts
Remove a field
This policy removes the email field from each event and keeps the other
fields, including id.
modules/notification-events.ts
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.
modules/notification-events.ts
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:
modules/shared.ts
The SSE policy and the WebSocket outbound message policy each call the shared functions:
modules/sse-policies.ts
modules/websocket-policies.ts
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.
modules/sse-policies-outbound.ts
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
ssePoliciesto one fails the build.
Related documentation
- URL Forward Handler
- URL Rewrite Handler
- WebSocket Pipeline Handler - message policies for WebSocket routes
- Streaming responses and Server-Sent Events