Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 39 ยท Beyond Fetch

Streaming and Real-Time APIs

Read response streams with fetch, listen to Server-Sent Events, open WebSockets, share messages between tabs with BroadcastChannel and pick the right tool.

A plain fetch() call is a question and an answer: you ask, the server replies, the conversation is over. Many features need more than that. A chat app must show a message the moment someone else sends it. A progress bar needs updates while a report is being generated. A large download should be processed piece by piece instead of waiting for the last byte. A dashboard should refresh when the data changes, not every thirty seconds.

This lesson covers the tools for those jobs: response streams (one response that arrives in pieces), Server-Sent Events (the server pushes messages over one long HTTP response), WebSockets (a two-way channel) and BroadcastChannel (messages between tabs of the same browser). It also gives you a decision guide, because the best answer is often the simplest one. If you want polling instead, see caching and polling.

A sandboxed example page has no server it can keep a connection to, so the live demos here are local simulations: a fake streaming response made in the page, the real parsing code for the event-stream format, and real BroadcastChannel objects. Code that needs a real server (EventSource, WebSocket) is shown read-only and is the same code you would deploy.

Reading a response as a stream

When you call response.json() or response.text(), the browser waits for the whole body before giving it to you. But response.body is a ReadableStream: you can read it chunk by chunk as the bytes arrive. That helps in three situations: showing download progress, starting to render a huge result before it is complete and handling endless responses such as a log feed.

JavaScript
const response = await fetch("/api/export.csv");
const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();   // value is a Uint8Array chunk
  if (done) break;
  handleText(decoder.decode(value, { stream: true }));
}

reader.read() returns a promise for { done, value }. The chunks are bytes, not text, and a chunk boundary can fall in the middle of a multi-byte character, which is why TextDecoder takes { stream: true }: it keeps incomplete characters until the next chunk arrives. Total size comes from the Content-Length header when the server sends one (response.headers.get("Content-Length")), which lets you compute a percentage; with compression the header may describe the compressed size, so treat it as a rough guide. Modern browsers also let you loop with for await (const chunk of response.body), but getReader() works everywhere.

The next demo builds a response from a stream that pushes a chunk every 300 ms, so you can see progress build up without any network.

JS Reading a streamed response

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

No output.

Streams can also be cancelled with reader.cancel() or an AbortSignal, which tells the browser to stop downloading. The same mechanism handles the streaming responses of many AI and log APIs, which send newline-delimited JSON (one JSON value per line, see nested JSON and NDJSON).

Server-Sent Events

Server-Sent Events (SSE) is the simplest real-time technology. The browser opens one ordinary HTTP request, the server never finishes the response, and each time it has news it writes a small text message. Data flows in one direction only, server to client, which fits notifications, live scores, stock prices, progress updates and log tailing.

The browser gives you a built-in class, EventSource, that handles the connection, parses the messages and reconnects automatically when the connection drops. Here is a typical client (read-only, because the sandbox has no server to connect to):

JavaScript
const source = new EventSource("/api/notifications");

source.addEventListener("message", (event) => {
  const note = JSON.parse(event.data);
  showNotification(note.text);
});

source.addEventListener("price", (event) => {          // a named event type
  updatePrice(JSON.parse(event.data));
});

source.addEventListener("error", () => {
  // The browser will retry by itself; readyState tells you what is happening
  console.log(source.readyState === EventSource.CLOSED ? "closed" : "reconnecting");
});

// Later, when the page no longer needs updates:
source.close();

On the wire the format is plain text with the media type text/event-stream. Messages are separated by a blank line, and each line has a field name, a colon and a value:

TEXT
event: price
id: 42
data: {"symbol":"ACME","value":18.2}

data: a message without a named event type
data: continued on a second data line

: this line is a comment, often used as a keep-alive
retry: 5000

The fields mean: data is the payload (several data: lines are joined with newlines), event names the event type (the default is message), id sets the last event ID that the browser sends back in a Last-Event-ID header when it reconnects so the server can resume, and retry sets the reconnect delay in milliseconds. A line starting with a colon is a comment. EventSource can only do GET requests and cannot set custom headers, which makes bearer-token authentication awkward; cookies work, or you can read the same format yourself with fetch() and a stream.

Reading the format yourself is also a good way to understand it. This demo feeds an event-stream text through a stream in odd-sized chunks (as a real network might) and parses it with a small function that handles chunk boundaries correctly.

JS Parsing a Server-Sent Events stream

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

No output.

The loop buffers incoming text until it sees a blank line, which is why chunk size does not matter. You rarely write this yourself because EventSource does it, but the same pattern is how you handle streaming APIs that use the event-stream format over POST requests.

WebSockets

A WebSocket is a persistent, two-way connection. It starts as an HTTP request that asks to "upgrade" the connection; after that, both sides can send messages at any time with very little overhead per message. Chat applications, multiplayer games, collaborative editors and trading screens use WebSockets because the client talks as often as the server does.

JavaScript
const socket = new WebSocket("wss://chat.example.com/room/7");   // wss = encrypted, like https

socket.addEventListener("open", () => {
  socket.send(JSON.stringify({ type: "join", user: "mira" }));
});

socket.addEventListener("message", (event) => {
  const message = JSON.parse(event.data);               // data is a string (or Blob)
  addMessageToChat(message);
});

socket.addEventListener("close", (event) => {
  console.log("closed", event.code, event.reason);
  // reconnect with a delay, see below
});

socket.addEventListener("error", () => console.log("socket error"));

Compared with SSE, a WebSocket gives you more freedom and also more work, because nothing is done for you:

  • No automatic reconnect. When the connection drops (a phone changes networks, a proxy times out idle sockets), you must reconnect yourself, ideally with the exponential backoff you saw earlier, and ask the server for the messages you missed.
  • No message format. You decide what a message looks like. JSON with a type field is the usual choice.
  • No backpressure by default. If you send faster than the network accepts, socket.bufferedAmount grows; check it before sending large amounts.
  • Authentication is up to you. Browsers cannot add an Authorization header to a WebSocket handshake. Teams use a cookie, a short-lived token in the URL or a first message that authenticates. Short-lived tokens matter, because URLs end up in logs.
  • Keep-alive. Servers often send periodic ping messages; the browser answers them automatically.

Always validate incoming messages (see validating JSON data) and render them safely, because a chat message is user-generated content from other people.

sequenceDiagram
  participant C as Client
  participant S as Server
  C->>S: HTTP GET with Upgrade: websocket
  S-->>C: 101 Switching Protocols
  C->>S: message (join)
  S-->>C: message (welcome)
  S-->>C: message (someone wrote)
  C->>S: message (my reply)
  C->>S: close

After the 101 response the HTTP request is over and both sides send messages freely.

BroadcastChannel: talking between tabs

Sometimes the "other side" is not a server but another tab, window or iframe of your own site. With BroadcastChannel, every object created with the same channel name (in the same origin) receives the messages the others post. It is a good fit for syncing a logout across tabs, sharing a theme choice or coordinating so that only one tab polls the server.

Messages are copied with the structured clone algorithm, so objects, arrays, dates and maps work without JSON.stringify(). A channel never delivers a message to the object that sent it, only to the others. The demo creates two channel objects in one page, which behave like two tabs. Because sandboxed previews can restrict features, the code checks for support first.

JS Two channels talking to each other

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

No output.

Remember to call close() when a channel is no longer needed. BroadcastChannel only works within one browser profile and one origin; it is not a network feature, and it cannot reach other users.

Choosing: polling, SSE or WebSockets

Start with the least powerful tool that does the job.

Need Best fit Why
Data that changes rarely, any latency is fine Plain polling Simplest, works with caches and every server
Server-to-client updates in near real time SSE Plain HTTP, automatic reconnect, easy to scale behind normal proxies
Frequent messages in both directions, low latency WebSocket One connection, small messages
Big download, progress, NDJSON or AI responses Streamed fetch() One response read in pieces
Sync between tabs of one site BroadcastChannel No server needed

Some cautions apply to all of them. Each open connection uses server memory, so thousands of users means thousands of connections, and your server software must be built for it. Browsers limit connections per host (with HTTP/1.1 only a handful of SSE streams per domain), so do not open one connection per widget; share one and dispatch messages inside the page. And close connections when users leave (source.close(), socket.close(), reader.cancel()), especially in single-page apps where components appear and disappear.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is response.body in a fetch response?

    response.body is a ReadableStream. Methods like json() and text() read all of it and parse it for you.
  2. 2. Why does TextDecoder need { stream: true } when decoding chunks?

    With stream: true the decoder holds an incomplete character instead of producing a broken one.
  3. 3. Which feature does EventSource give you that a raw WebSocket does not?

    EventSource reconnects by itself and sends Last-Event-ID. With WebSockets you write the reconnect logic.
  4. 4. A live auction page needs bids in both directions with very low delay. What fits best?

    Frequent two-way messages are the WebSocket use case. BroadcastChannel never leaves the browser.
  5. 5. A tab posts a message on a BroadcastChannel. Who receives it?

    BroadcastChannel is local to one browser profile and origin, and the posting object does not receive its own message.

Summary

  • response.body is a stream: read it with getReader() for progress, large downloads or NDJSON, and decode with TextDecoder using { stream: true }.
  • Server-Sent Events push text messages in one direction over a long HTTP response; EventSource parses them and reconnects automatically.
  • WebSockets are two-way and low overhead, but you must add reconnection, message formats, authentication and validation yourself.
  • BroadcastChannel sends structured-cloneable messages between tabs of the same origin; it never reaches the network.
  • Pick the simplest tool that fits: polling, then SSE, then WebSockets; always close connections you no longer need.

Next: AJAX Security covers the risks that come with putting API data into a page.