Skip to content

Instantly share code, notes, and snippets.

@jrosell
Created March 2, 2026 20:43
Show Gist options
  • Select an option

  • Save jrosell/178ed4fab7189ed64f472b8e3bf3a068 to your computer and use it in GitHub Desktop.

Select an option

Save jrosell/178ed4fab7189ed64f472b8e3bf3a068 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