Helper function to format messages according to the Server-Sent Events (SSE)
specification. Use with handler_stream() to create SSE endpoints.
Details
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:
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-streamCache-Control: no-cacheX-Accel-Buffering: no(prevents proxy buffering)
See also
handler_stream() for creating streaming HTTP endpoints.
Examples
format_sse(data = "Hello")
#> [1] "data: Hello\n\n"
#> "data: Hello\n\n"
format_sse(data = "Hello", event = "greeting")
#> [1] "event: greeting\ndata: Hello\n\n"
#> "event: greeting\ndata: Hello\n\n"
format_sse(data = "Line 1\nLine 2")
#> [1] "data: Line 1\ndata: Line 2\n\n"
#> "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"))
})
