Skip to main content
The Sse response type enables streaming events to clients using the Server-Sent Events (SSE) protocol. SSE is a simple HTTP-based protocol for pushing updates from the server to the client.

Basic usage

Return a stream of events wrapped in Sse:
Example from axum/src/response/sse.rs:6-26 and examples/sse/src/main.rs.

How it works

IntoResponse implementation

The Sse type sets proper headers and wraps the stream in a body:
See implementation in axum/src/response/sse.rs:90-107.

Response fields

header
Automatically set to text/event-stream
header
Automatically set to no-cache
stream
A stream of SSE events formatted according to the SSE protocol

Event API

Creating events

Event fields

string
The event payload. Corresponds to MessageEvent.data in the browser. Newlines are automatically handled with multiple data: fields.
string
The event type. Used with addEventListener(type, ...) in the browser. Defaults to "message" if not set.
string
Event identifier. Sets MessageEvent.lastEventId in the browser. Cannot contain newlines or null characters.
Duration
Reconnection timeout hint for the client in milliseconds.
string
Comment field (ignored by most clients). Can be called multiple times. Cannot contain newlines.

JSON data

See axum/src/response/sse.rs:246-277.

Custom data writer

For advanced use cases, write data incrementally:
See axum/src/response/sse.rs:179-222.

Keep-alive

Keep connections alive by sending periodic messages:

KeepAlive configuration

Duration
Time between keep-alive messages. Default is 15 seconds.
string
Custom keep-alive message text. Default is an empty comment.
Event
Custom keep-alive event. Allows full control over the keep-alive message.
See implementation in axum/src/response/sse.rs:514-573.

Complete example

Browser usage

See also