% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/server.R
\name{format_sse}
\alias{format_sse}
\title{Format Server-Sent Event}
\usage{
format_sse(data, event = NULL, id = NULL, retry = NULL)
}
\arguments{
\item{data}{The data payload. Will be prefixed with "data: " on each line.}

\item{event}{[default NULL] Optional event type (e.g., "message", "error").}

\item{id}{[default NULL] Optional event ID for client reconnection.}

\item{retry}{[default NULL] Optional retry interval in milliseconds.}
}
\value{
A character string formatted as an SSE message, ready to pass to
\code{conn$send()}.
}
\description{
Helper function to format messages according to the Server-Sent Events (SSE)
specification. Use with \code{\link[=handler_stream]{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 \code{EventSource} API. SSE is
commonly used for real-time updates, notifications, and LLM token streaming.

SSE messages have this format:

\if{html}{\out{<div class="sourceCode">}}\preformatted{event: <event-type>
id: <event-id>
retry: <milliseconds>
data: <data-line-1>
data: <data-line-2>

}\if{html}{\out{</div>}}

Each message ends with two newlines. Multi-line data is split and each
line prefixed with "data: ".

When using SSE with \code{\link[=handler_stream]{handler_stream()}}, set the appropriate headers:
\itemize{
\item \code{Content-Type: text/event-stream}
\item \code{Cache-Control: no-cache}
\item \code{X-Accel-Buffering: no} (prevents proxy buffering)
}
}
\examples{
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"))
})

}
\seealso{
\code{\link[=handler_stream]{handler_stream()}} for creating streaming HTTP endpoints.
}
