Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 37 ยท HTTP Servers

Streaming, Server-Sent Events and WebSockets in Deno

Send data to clients as it is produced. Stream response bodies, push Server-Sent Events, upgrade connections to WebSockets with Deno.upgradeWebSocket and build a broadcast hub.

A normal response is built completely and then sent. Many useful features do not fit that shape: a progress log that grows while a job runs, a live price ticker, a chat room. For these the server must keep the connection open and send pieces over time. Deno supports three ways to do that, and all are built on web standards: streaming response bodies, Server-Sent Events (SSE) and WebSockets.

This lesson shows each one, explains when to choose which, and ends with a broadcast hub that powers chat-style apps. The same patterns are used in the real-time chat project.

Deno is not available on this site, so Deno.* code is read-only. The runnable examples use Node 24, which has the same ReadableStream, Response and TextEncoder classes. Real network sockets are replaced by small stand-in objects that behave like a WebSocket.

Streaming a response body

A Response body may be a ReadableStream. Whatever you enqueue is sent to the client right away, and the connection stays open until you close the stream.

TypeScript
Deno.serve((_req) => {
  const encoder = new TextEncoder();
  let n = 0;

  const body = new ReadableStream({
    start(controller) {
      controller.enqueue(encoder.encode("starting\n"));
    },
    async pull(controller) {
      await new Promise((r) => setTimeout(r, 500));
      n++;
      controller.enqueue(encoder.encode(`step ${n}\n`));
      if (n === 5) controller.close();
    },
    cancel() {
      console.log("client went away");
    },
  });

  return new Response(body, { headers: { "content-type": "text/plain" } });
});

pull is called when the client can take more data, which gives you backpressure for free: a slow client does not make the server buffer without limit. cancel runs when the client disconnects, which is where you clean up timers and subscriptions.

You also get streams from other places and can pass them straight through. For example, proxying a file without loading it into memory:

TypeScript
const file = await Deno.open("./big.log", { read: true });
return new Response(file.readable);

The next example reads a streamed response the way a client would, chunk by chunk, so you can see the data arrive in pieces.

Node.js Producing and consuming a stream

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

SSE is a very simple protocol for one-way push from server to browser: a response with content-type: text/event-stream whose body is lines of text. The browser's EventSource class parses it and reconnects automatically.

An event looks like this on the wire. A blank line ends the event:

TEXT
event: price
id: 42
data: {"symbol":"DENO","value":10.5}

data: a plain message without a name

TypeScript
// server
Deno.serve((req) => {
  if (new URL(req.url).pathname !== "/events") {
    return new Response("not found", { status: 404 });
  }
  let timer: number;
  const body = new ReadableStream({
    start(controller) {
      const enc = new TextEncoder();
      let id = 0;
      timer = setInterval(() => {
        id++;
        controller.enqueue(enc.encode(`id: ${id}\ndata: tick ${id}\n\n`));
      }, 1000);
    },
    cancel() {
      clearInterval(timer);
    },
  });
  return new Response(body, {
    headers: {
      "content-type": "text/event-stream",
      "cache-control": "no-cache",
    },
  });
});
HTML
<script>
  const source = new EventSource("/events");
  source.onmessage = (e) => console.log(e.data);
  source.addEventListener("price", (e) => console.log(JSON.parse(e.data)));
</script>

If the connection drops, EventSource reconnects and sends the last id in a Last-Event-ID header, so the server can resume. The standard library also has ServerSentEventStream in jsr:@std/http/server-sent-event-stream, a TransformStream that formats events for you.

The format code is tiny and easy to get wrong, so here it is as a tested function.

Node.js Formatting and parsing SSE

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.

Choose SSE over WebSockets when data flows only from server to client (notifications, dashboards, progress, LLM token streams). It works through plain HTTP infrastructure, needs no extra protocol and reconnects on its own. Remember that browsers limit parallel HTTP/1.1 connections per host, so prefer HTTP/2 or HTTPS in production.

WebSockets with Deno.upgradeWebSocket

When both sides must send messages at any time, use a WebSocket. A client starts with an ordinary HTTP request that has an Upgrade: websocket header; Deno.upgradeWebSocket(req) answers it and gives you the socket.

TypeScript
Deno.serve((req) => {
  if (req.headers.get("upgrade") !== "websocket") {
    return new Response("Expected a WebSocket", { status: 426 });
  }

  const { socket, response } = Deno.upgradeWebSocket(req, {
    idleTimeout: 30,   // seconds without traffic before pings fail the socket
  });

  socket.onopen = () => socket.send("welcome");
  socket.onmessage = (event) => socket.send(`echo: ${event.data}`);
  socket.onclose = () => console.log("closed");
  socket.onerror = (e) => console.error("socket error", e);

  return response;   // must return this to complete the handshake
});

The socket is the standard WebSocket class, so the browser side is the same API:

JavaScript
const ws = new WebSocket("ws://localhost:8000");
ws.onmessage = (e) => console.log(e.data);
ws.onopen = () => ws.send("hello");

Important rules: check socket.readyState === WebSocket.OPEN before sending, validate every incoming message (it is untrusted text or bytes), check the Origin header if browsers from other sites must not connect, and cap message size and rate.

A broadcast hub

Chat, presence and collaborative tools need to send one message to many sockets. Keep a Set of connected sockets, add on open, remove on close, and loop on message.

Node.js A broadcast hub with stand-in sockets

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.

In a Deno server the join call goes in onopen, message in onmessage and leave in onclose. One caveat: this hub lives in the memory of one process. If your app runs several instances or isolates, a message sent to one never reaches sockets on another. BroadcastChannel connects isolates on the same Deno Deploy region, and Deno KV watch and queues or an external pub/sub system connect everything else.

Which one should I use?

Need Use
Large download, log tail, generated file Streaming response
Server pushes updates, client only listens SSE
Two-way, low latency, many small messages WebSocket
Binary data in both directions WebSocket

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which content type marks a response as a Server-Sent Events stream?

    Browsers only treat the response as an event stream when it is served as text/event-stream.
  2. 2. What must the handler return after calling Deno.upgradeWebSocket(req)?

    The returned response completes the HTTP upgrade handshake. Returning anything else leaves the client without a WebSocket.
  3. 3. Why does a Set-based broadcast hub fail when an app runs on several servers?

    A hub in memory is per process. Cross-process delivery needs a shared channel such as BroadcastChannel, KV or a message broker.
  4. 4. When is SSE a better fit than a WebSocket?

    SSE is plain HTTP, one directional, and EventSource reconnects automatically, which suits notifications and dashboards.

Summary

  • A ReadableStream body streams data as it is produced; use pull for backpressure and cancel for cleanup.
  • SSE sends text/event-stream lines (event, id, data) and EventSource reconnects automatically.
  • Deno.upgradeWebSocket(req) returns { socket, response }; always return the response.
  • Validate every incoming message and check readyState before sending.
  • A Set of sockets makes a broadcast hub, but it only spans one process.

Next: Writing Tests with deno test