Sub topic 10
Reading the stream with fetch in the browser
This chapter assumes you know basic HTTP, JSON, and JavaScript promises with async/await. You should also know the Server-Sent Events (SSE) format from the earlier chapters: events end with a blank line, and payload lines start with data:.
Why not EventSource?
The browser's built-in EventSource only sends GET requests and cannot set a request body or custom headers. Chat requests usually need a POST with a JSON body and often an Authorization header. So you read the response body yourself with fetch.
The reading loop
fetch resolves as soon as the response headers arrive. The body is then available as response.body, a ReadableStream of bytes. The steps are:
- Send the request and check
response.ok. - Pipe the body through a
TextDecoderStreamto turn bytes into text. - Call
reader.read()in a loop untildoneis true. - Append each text chunk to a buffer, split the buffer into complete events, and keep the incomplete tail.
async function streamCompletion(url, body, onData, signal) {
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
signal,
});
if (!response.ok || !response.body) {
throw new Error(`Request failed with status ${response.status}`);
}
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += value;
// Events end with a blank line; keep any incomplete tail for the next chunk.
const events = buffer.split("\n\n");
buffer = events.pop();
for (const event of events) {
for (const line of event.split("\n")) {
if (line.startsWith("data: ")) onData(line.slice(6));
}
}
}
}
const controller = new AbortController();
// Call controller.abort() from a "Stop" button to cancel the request.
streamCompletion("/api/chat", { prompt: "Hello" }, (data) => console.log(data), controller.signal);Why the buffer matters
A network chunk is not an event. One chunk can hold half an event, or three events and the start of a fourth. If you parsed each chunk on its own, you would sometimes get broken JSON. The line events = buffer.split("\n\n") followed by buffer = events.pop() handles this. The last element of the split is always either an empty string or an unfinished event, so it goes back into the buffer.
TextDecoderStream also matters. A multi-byte character such as an emoji can be split across two chunks. The stream decoder holds the partial bytes until the rest arrive. Calling new TextDecoder().decode(chunk) on each chunk without the stream option would corrupt such characters.
Using the data
The onData callback receives the payload string. In an LLM stream, that is usually a JSON delta, or a sentinel such as [DONE]. Handle the sentinel before calling JSON.parse:
let text = "";
function onData(data) {
if (data === "[DONE]") return;
const delta = JSON.parse(data).delta;
text += delta;
document.querySelector("#output").textContent = text;
}Use textContent, not innerHTML, for model output. Model text can contain markup, and inserting it as HTML opens the page to script injection.
Common errors
- Checking only the promise.
fetchdoes not reject on HTTP 4xx or 5xx. Checkresponse.okbefore reading. - Ignoring
\r\n. Some servers use\r\n\r\nbetween events. Normalize line endings if you do not control the server. - Treating abort as failure. Calling
controller.abort()makesfetchorreader.read()reject with anAbortError. Catch it and treat it as a normal stop. - Reading from a buffered server. If everything arrives at once, the cause is often a proxy, not your loop. A later chapter covers this.
Exercise
A chunk arrives containing data: {"delta": "Hel"}\n\ndata: {"del. What does the loop do with it, and why is the last part not passed to onData?
Show answer
Splitting on a blank line gives two elements: the complete event data: {"delta": "Hel"} and the fragment data: {"del. events.pop() removes the fragment and stores it in buffer. Only the complete event reaches onData. When the next chunk arrives, it is appended to the fragment, so the second event is parsed whole.
Exercise
A user clicks "Stop" and your console shows an uncaught AbortError. What should you change?
Show answer
Wrap the call to streamCompletion in a try/catch. If error.name === "AbortError", treat it as a normal stop and keep the text received so far. Rethrow or display any other error.