| format_sse | R Documentation |
Helper function to format messages according to the Server-Sent Events (SSE)
specification. Use with handler_stream() to create SSE endpoints.
format_sse(data, event = NULL, id = NULL, retry = NULL)
data |
The data payload. Will be prefixed with "data: " on each line. |
event |
[default NULL] Optional event type (e.g., "message", "error"). |
id |
[default NULL] Optional event ID for client reconnection. |
retry |
[default NULL] Optional retry interval in milliseconds. |
Server-Sent Events is a W3C standard for server-to-client streaming over
HTTP, supported natively by browsers via the EventSource API. SSE is
commonly used for real-time updates, notifications, and LLM token streaming.
SSE messages have this format:
event: <event-type> id: <event-id> retry: <milliseconds> data: <data-line-1> data: <data-line-2>
Each message ends with two newlines. Multi-line data is split and each line prefixed with "data: ".
When using SSE with handler_stream(), set the appropriate headers:
Content-Type: text/event-stream
Cache-Control: no-cache
X-Accel-Buffering: no (prevents proxy buffering)
A character string formatted as an SSE message, ready to pass to
conn$send().
handler_stream() for creating streaming HTTP endpoints.
format_sse(data = "Hello")
#> "data: Hello\n\n"
format_sse(data = "Hello", event = "greeting")
#> "event: greeting\ndata: Hello\n\n"
format_sse(data = "Line 1\nLine 2")
#> "data: Line 1\ndata: Line 2\n\n"
# Typical SSE endpoint setup
h <- handler_stream("/events", function(conn, req) {
conn$set_header("Content-Type", "text/event-stream")
conn$set_header("Cache-Control", "no-cache")
conn$set_header("X-Accel-Buffering", "no")
conn$send(format_sse(data = "connected", id = "1"))
})
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.