Last active
January 5, 2026 11:20
-
-
Save ForbesLindesay/61540ab1b5f88d731a502ed3dadf2414 to your computer and use it in GitHub Desktop.
ServerSentEventsStream Koa Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | |
| }, | |
| }) | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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