Skip to content

Instantly share code, notes, and snippets.

@ForbesLindesay
Last active January 5, 2026 11:20
Show Gist options
  • Select an option

  • Save ForbesLindesay/61540ab1b5f88d731a502ed3dadf2414 to your computer and use it in GitHub Desktop.

Select an option

Save ForbesLindesay/61540ab1b5f88d731a502ed3dadf2414 to your computer and use it in GitHub Desktop.
ServerSentEventsStream Koa Example
import { TransformStream } from "stream/web"
export default class ServerSentEventsStream extends TransformStream<unknown, string> {
constructor() {
super({
async transform(message, controller) {
controller.enqueue(`data: ${JSON.stringify(message)}` + "\n\n")
},
})
}
}
import { Readable } from "stream"
import ServerSentEventsStream from "./ServerSentEventsStream"
function sendResponse(ctx: KoaContext) {
ctx.setHeader("Content-Type", "text/event-stream")
ctx.setHeader("Cache-Control", "no-cache")
ctx.setHeader("X-Accel-Buffering", "no")
ctx.body = Readable.fromWeb(
getEventsStream()
.pipeThrough(new ServerSentEventsStream())
.pipeThrough(new TextEncoderStream())
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment