Server-Sent Event (SSE) generator for streaming updates to clients.
This module provides functionality for creating and managing SSE connections, sending events, and handling the streaming lifecycle.
Example
conn
|> put_resp_content_type("text/event-stream")
|> send_chunked(200)
|> PhoenixDatastar.SSE.new()
|> PhoenixDatastar.SSE.send_event("my-event", "data content")
Summary
Functions
Marks the SSE connection as closed.
Checks if the SSE connection is closed.
Formats a single SSE event as a string (for non-streaming responses).
Creates a new SSE generator from a Plug connection.
Sends an SSE event to the client.
Sends an SSE event and raises on error.
Types
@type t() :: %PhoenixDatastar.SSE{closed: boolean(), conn: Plug.Conn.t()}
Functions
Marks the SSE connection as closed.
Checks if the SSE connection is closed.
Formats a single SSE event as a string (for non-streaming responses).
This is useful for stateless views that return SSE-formatted responses directly in a single HTTP response body rather than via chunked streaming.
Parameters
event_type- The event type (e.g., "datastar-patch-elements")data_lines- A list of data lines
Example
format_event("datastar-patch-elements", [
"selector #count",
"mode outer",
"elements <span>42</span>"
])
# => "event: datastar-patch-elements\ndata: selector #count\ndata: mode outer\ndata: elements <span>42</span>\n\n"
@spec new(Plug.Conn.t()) :: t()
Creates a new SSE generator from a Plug connection.
The connection must already have:
- Content type set to "text/event-stream"
- Response status set
- Chunked response initiated via
send_chunked/2
Example
conn
|> put_resp_content_type("text/event-stream")
|> send_chunked(200)
|> PhoenixDatastar.SSE.new()
@spec send_event(t(), String.t(), [String.t()] | String.t(), keyword()) :: {:ok, t()} | {:error, term()}
Sends an SSE event to the client.
Parameters
sse- The SSE generator structevent_type- The event type (e.g., "datastar-patch-elements")data_lines- A list of data lines or a single stringopts- Optional keyword list with::event_id- Event ID for client tracking:retry- Retry duration in milliseconds
Example
sse
|> send_event("my-event", ["line1", "line2"], event_id: "123", retry: 5000)
Sends an SSE event and raises on error.
Same as send_event/4 but raises if the event cannot be sent.
Returns the updated SSE generator on success.
Example
sse
|> send_event!("my-event", "data")
|> send_event!("another-event", "more data")