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 inSse:
axum/src/response/sse.rs:6-26 and examples/sse/src/main.rs.
How it works
IntoResponse implementation
TheSse type sets proper headers and wraps the stream in a body:
axum/src/response/sse.rs:90-107.
Response fields
header
Automatically set to
text/event-streamheader
Automatically set to
no-cachestream
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
axum/src/response/sse.rs:246-277.
Custom data writer
For advanced use cases, write data incrementally: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.
axum/src/response/sse.rs:514-573.
Complete example
Browser usage
See also
- Streaming responses for binary streaming
- IntoResponse trait for custom response types
- MDN: Server-Sent Events