Sub topic 10
Reading the stream with fetch in the browser
This chapter assumes you know how Server-Sent Events (SSE) frame data, as covered earlier. It also assumes you are comfortable with promises, async/await, and JSON. Here you will read a streamed LLM response in the browser, handle the places where chunks split events, and let the user cancel.
Why fetch and not EventSource
The browser has a built-in SSE client called EventSource. It is a poor fit for most LLM chat endpoints, for three reasons:
- It can only send
GETrequests, so a long prompt or message history cannot go in a JSON body. - It cannot set custom headers, so you cannot send an
Authorizationheader. - It reconnects automatically when the connection drops. For a chat completion, a reconnect would start a new generation and bill you for it.
fetch has none of these limits. You choose the method, headers, and body. The cost is that you parse the SSE format yourself, which the rest of this chapter covers.
| Feature | `EventSource` | `fetch` with a stream reader |
|---|---|---|
| HTTP method | GET only | Any |
| Request body | No | Yes |
| Custom headers | No | Yes |
| SSE parsing | Built in | You write it |
| Automatic reconnect | Yes | No |
| Cancellation | `close()` | `AbortController` |
The shape of the response body
When fetch resolves, the promise gives you a Response as soon as the status line and headers arrive. The body has not finished downloading at that point. response.body is a ReadableStream of Uint8Array chunks, and you pull chunks from it as they arrive.
The loop from the buffer back to itself matters. The last piece after a split may be half an event, so you keep it and prepend it to the next chunk.
Decoding bytes safely
Chunk boundaries are set by the network and have nothing to do with characters. A UTF-8 character such as é or an emoji takes several bytes, and a chunk can end partway through one. Calling new TextDecoder().decode(chunk) on each chunk separately would corrupt such characters.
Two correct options exist:
response.body.pipeThrough(new TextDecoderStream())keeps decoder state between chunks.- A single
TextDecoderwithdecode(chunk, { stream: true })does the same when you read raw bytes.
A complete stream reader
This function posts a request, checks the status, decodes the body, buffers partial events, and calls onData for each data: payload. It also normalizes \r\n line endings, which some servers and proxies send.
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) {
const detail = await response.text().catch(() => "");
throw new Error(`Request failed with status ${response.status}: ${detail}`);
}
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += value.replace(/\r\n/g, "\n");
// An event ends with a blank line. Keep the incomplete tail.
const events = buffer.split("\n\n");
buffer = events.pop();
for (const event of events) {
const dataLines = [];
for (const line of event.split("\n")) {
if (line.startsWith("data:")) {
dataLines.push(line.slice(5).replace(/^ /, ""));
}
}
if (dataLines.length > 0) onData(dataLines.join("\n"));
}
}
}A few details are worth checking in this code:
- Comment lines that start with
:are ignored because onlydata:lines are collected. - Several
data:lines in one event are joined with\n, as the SSE format requires. - Only one leading space after the colon is removed, so payloads with meaningful spaces survive.
- A
\r\npair split across two chunks (the\rat the end of one, the\nat the start of the next) would slip past the regex. If you must support servers that send CRLF, normalize after the whole buffer is assembled, or use a maintained parser library.
Handling the payloads
The reader is generic. The caller decides what a payload means. For an OpenAI-style stream, each payload is a JSON string and the last one is the literal [DONE].
let text = "";
function onData(payload) {
if (payload === "[DONE]") return;
const event = JSON.parse(payload);
const piece = event.choices?.[0]?.delta?.content;
if (piece) {
text += piece;
document.querySelector("#output").textContent = text;
}
}The field path differs between providers, so check the delta format of the API you use. Setting textContent rather than innerHTML keeps model output from being interpreted as markup.
Flushing the final buffer
The loop above drops whatever remains in buffer when the stream ends. Well-behaved servers finish with a blank line, so nothing is lost. A server that closes the connection mid-event leaves an incomplete fragment, and discarding it is usually the right choice. A truncated JSON payload would only throw in JSON.parse.
Cancelling with AbortController
Pass an AbortSignal to fetch and call abort() to stop. The pending reader.read() rejects with a DOMException whose name is "AbortError". The browser closes the connection, and a well-configured server notices and stops generating.
const controller = new AbortController();
const stopButton = document.querySelector("#stop");
stopButton.onclick = () => controller.abort();
try {
await streamCompletion(
"/api/chat",
{ prompt: "Write a long story." },
onData,
controller.signal
);
} catch (err) {
if (err.name === "AbortError") {
console.log("Stopped by the user. Partial text is kept:", text);
} else {
console.error("Stream failed:", err);
}
}An abort is a user decision and not a failure, so keep the partial text and do not show an error banner. Create a fresh AbortController for every request, because a controller cannot be reset after abort().
Failures you will meet
Errors come in two phases, and each needs different handling.
- Before streaming starts. The server answers with a normal error status such as 401, 429, or 500 and a JSON body. This is why the code checks
response.okbefore reading the stream. If you skip the check, the reader will treat the error JSON as a stream and produce nothing. - After streaming starts. The status is already 200 and cannot change. A failure now appears as a network error that rejects
reader.read(), as a premature end of stream, or as an error event inside the stream, depending on the server. Treat a stream that ends without[DONE]or a finish reason as incomplete.
Common mistakes to look for when output arrives all at once or is garbled:
- Everything appears at the end. A proxy or the server is buffering. Check headers such as
Cache-Control: no-cacheandX-Accel-Buffering: no, and test withcurl -Nto see whether the problem is in the browser or earlier. JSON.parsefails sometimes. You are parsing per chunk instead of per event, so a split event reaches the parser incomplete.- Accented or emoji characters turn into
�. You decoded each chunk separately withoutstream: true. - Reading
response.json()on a stream. This waits for the whole body, which removes the benefit of streaming. - A second
getReader()throws. A body stream can only be locked by one reader. Do not read it twice.
Summary of the browser side
- Use
fetchwhen you need POST bodies, headers, or control over retries. - Decode with
TextDecoderStreamorTextDecoderusingstream: true. - Split on blank lines, keep the tail, and parse one event at a time.
- Check
response.okfirst, and treatAbortErroras a normal stop.
Exercise
Your stream reader works on short replies but occasionally throws "Unexpected end of JSON input" on long ones. The code calls JSON.parse on every decoded chunk. What is the cause, and what change fixes it?
Show answer
Network chunks do not align with SSE event boundaries, so a chunk can contain half of an event. Parsing it fails because the JSON is incomplete. Append each decoded chunk to a buffer, split the buffer on a blank line ("\n\n"), keep the last (possibly incomplete) piece in the buffer for the next chunk, and run JSON.parse only on each complete event's joined data lines.
Exercise
A user clicks Stop and your page shows a red "Request failed" message. How should the catch block change, and why do you create a new AbortController for each request?
Show answer
Check err.name === "AbortError" and treat it as a normal stop: keep the partial text and show no error. Other errors still go to the error display. A controller's signal stays aborted permanently after abort() is called, so reusing it would cancel the next request immediately.