Skip to content

Instantly share code, notes, and snippets.

@jimbrig
Forked from jrosell/sse.R
Created July 3, 2026 23:11
Show Gist options
  • Select an option

  • Save jimbrig/d97648b93d72687213d260dcbd0f5cae to your computer and use it in GitHub Desktop.

Select an option

Save jimbrig/d97648b93d72687213d260dcbd0f5cae to your computer and use it in GitHub Desktop.
HTTP streaming and Server-Sent Events in R with nanonext
# pak::pak("r-lib/nanonext")
library(nanonext)
conns <- list()
handlers <- list(
handler_stream("/stream",
on_request = function(conn, req) {
conn$set_header("Content-Type", "application/x-ndjson")
conns[[as.character(conn$id)]] <<- conn
conn$send('{"status":"connected"}\n')
},
on_close = function(conn) {
conns[[as.character(conn$id)]] <<- NULL
}
),
# POST endpoint triggers broadcast to all streaming clients
handler("/broadcast", function(req) {
msg <- paste0('{"msg":"', rawToChar(req$body), '"}\n')
lapply(conns, function(c) c$send(msg))
list(status = 200L, body = "sent")
}, method = "POST")
)
server <- http_server(
url = "http://127.0.0.1:8080",
handlers = handlers
)
server$start()
server$url
# Open in two terminals
# curl -X GET http://127.0.0.1:8080/stream
# curl -X GET http://127.0.0.1:8080/stream
# Send in another terminal
# curl -X POST http://127.0.0.1:8080/broadcast -H "Content-Type: application/json" -d 'hello world'
# Both clients recieve the message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment