Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 39 ยท HTTP Servers and APIs

Streaming Responses and Server-Sent Events

Stream data from a Bun server with ReadableStream, serve large files with Bun.file, push live updates with Server-Sent Events and handle client disconnects.

A normal response is built completely and then sent. For big files, long-running jobs or live feeds that is wasteful: the client waits for the first byte, and the server holds everything in memory. Streaming sends the response in pieces as they become available. Bun's Response accepts a web ReadableStream as its body, and Bun.file() objects are streamed for you.

Streaming a file

TypeScript
Bun.serve({
  routes: {
    "/video": () => new Response(Bun.file("./media/intro.mp4")),
    "/report.csv": () =>
      new Response(Bun.file("./data/report.csv"), {
        headers: { "Content-Disposition": 'attachment; filename="report.csv"' },
      }),
  },
});

When you pass a BunFile as the body, Bun sets Content-Type from the file extension, sets Content-Length, supports Range requests for seeking in videos, and uses the operating system's fast file-sending path, so nothing is copied into JavaScript memory. Never build a path from user input without checking it stays inside your folder (see Bun.file and Bun.write).

A ReadableStream body

You can create your own stream. start runs once; call controller.enqueue(chunk) for every piece and controller.close() at the end. Chunks are Uint8Arrays (use TextEncoder) unless you pipe through an encoder.

TypeScript
Bun.serve({
  fetch() {
    const encoder = new TextEncoder();
    const stream = new ReadableStream({
      async start(controller) {
        for (let i = 1; i <= 5; i++) {
          controller.enqueue(encoder.encode(`line ${i}\n`));
          await Bun.sleep(500);
        }
        controller.close();
      },
    });
    return new Response(stream, { headers: { "Content-Type": "text/plain; charset=utf-8" } });
  },
});

The client sees a line every half second instead of waiting 2.5 seconds for everything. curl -N http://localhost:3000 shows it live (-N disables curl's output buffering).

Bun also accepts an async generator or iterable as a response body in recent versions, which reads even more simply (new Response(async function* () { yield "a"; })). The ReadableStream form works everywhere, so we use it here.

Node.js Consuming a ReadableStream chunk by chunk

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Server-Sent Events

Server-Sent Events (SSE) are a one-way push channel over plain HTTP: the browser opens new EventSource("/events"), and the server keeps the response open and writes events. It is simpler than WebSockets when only the server talks (live dashboards, progress bars, notifications, AI token streaming), and it reconnects automatically.

The wire format is text. Each event is lines of field: value, ended by a blank line:

TEXT
event: tick
id: 7
data: {"n":7}

Respond with Content-Type: text/event-stream, Cache-Control: no-cache and keep writing:

TypeScript
Bun.serve({
  routes: {
    "/events": (req) => {
      const encoder = new TextEncoder();
      let timer: Timer;
      const stream = new ReadableStream({
        start(controller) {
          let n = 0;
          timer = setInterval(() => {
            n++;
            controller.enqueue(encoder.encode(`id: ${n}\nevent: tick\ndata: ${JSON.stringify({ n })}\n\n`));
          }, 1000);
        },
        cancel() {
          clearInterval(timer); // the client went away
        },
      });
      return new Response(stream, {
        headers: {
          "Content-Type": "text/event-stream",
          "Cache-Control": "no-cache",
          Connection: "keep-alive",
        },
      });
    },
  },
  idleTimeout: 0, // do not close quiet connections (max is 255 seconds otherwise)
});

Two details matter. First, Bun closes connections idle longer than idleTimeout seconds (default 10), so for SSE either send a comment line like : keep-alive\n\n every few seconds or raise the timeout. Second, cancel() on the stream is called when the client disconnects; use it to clear timers and unsubscribe, or you leak resources for every closed tab.

In the browser:

JavaScript
const source = new EventSource("/events");
source.addEventListener("tick", (e) => console.log(JSON.parse(e.data)));
source.onerror = () => console.log("reconnecting...");

EventSource sends Last-Event-ID when it reconnects, so a server can resume from the last id it sent.

Node.js Formatting and parsing SSE events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Streaming JSON lines

Not every stream needs the browser's EventSource. For API clients, NDJSON (one JSON object per line, Content-Type: application/x-ndjson) is easy to produce and consume. The client reads res.body, splits on newlines and parses each line. It suits log tailing and large exports where you do not want to build one giant array.

Backpressure and aborts

A ReadableStream with a pull(controller) method instead of start is pull-based: Bun calls pull only when the connection can take more data, so a slow client cannot make you buffer unlimited chunks. Prefer pull when the source is a database cursor or a file. And when you call another API with fetch inside a handler, pass req.signal as its signal so that the upstream request is cancelled when your own client disconnects.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What Content-Type does a Server-Sent Events response use?

    Browsers only treat a response as an event stream when it is text/event-stream.
  2. 2. What ends one SSE event on the wire?

    Events are made of field: value lines and terminated by an empty line.
  3. 3. Why implement cancel() on a stream used for a live feed?

    Without cleanup, each closed tab leaves a timer or subscription running.
  4. 4. What does passing a BunFile as a Response body give you?

    Bun streams files natively and sets the headers from the file.
  5. 5. A pull-based stream (pull) helps because...

    pull is called when there is room, so slow clients do not cause unbounded buffering.

Summary

  • A Response body can be a ReadableStream; send chunks with enqueue, finish with close.
  • new Response(Bun.file(path)) streams files with correct headers and range support.
  • SSE = text/event-stream + field: value lines + a blank line; EventSource reconnects automatically.
  • Handle idleTimeout and cancel() for long-lived connections.
  • Use pull for backpressure and pass req.signal to upstream calls.

Next: WebSockets and Pub/Sub