Sub topic 11
Streaming Large Responses
response.json() and response.text() wait until the entire body has arrived before they give you anything. For a small API response that is fine. For a 200 MB log file, a long CSV export, or a server that sends results a line at a time, waiting means a frozen progress bar, high memory use, and nothing on screen until the very end. This chapter shows how to read a body as it arrives, piece by piece, using the ReadableStream that every Response exposes as response.body.
This chapter assumes you are comfortable with async/await, try/catch, and the earlier chapters on the Response object, single-use bodies, and HTTP error handling. Async generators (async function*) appear once, and the chapter explains them where they are used.
What response.body Actually Is
response.body is a ReadableStream of bytes. The browser fills it as network packets arrive. The body-reading methods you already know (json(), text(), blob(), arrayBuffer()) are convenience functions. Each one reads that stream to the end and then converts the result.
When you read the stream yourself, you get the data in chunks. A chunk is a Uint8Array holding whatever bytes have arrived since the last read. You don't control chunk size. It depends on the network, the server, and the browser's buffering, so one chunk might be 16 KB and the next might be 300 bytes. Write your code so it works for any chunk size, including a chunk that ends halfway through a line or halfway through a multi-byte character.
| Approach | When you get data | Memory held | Typical use |
|---|---|---|---|
| `await response.json()` | After the last byte | Whole body plus parsed object | Normal API calls |
| `await response.blob()` | After the last byte | Whole body | Images, downloads |
| `response.body.getReader()` | Chunk by chunk | Whatever you choose to keep | Progress bars, huge files, line-by-line feeds |
The Read Loop
To read a stream you ask it for a reader. Each call to reader.read() returns a Promise that resolves to { done, value }. While data is flowing, done is false and value is a chunk. When the stream ends, done is true and value is undefined.
async function readTextStream(url) {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
if (!response.body) return '';
const reader = response.body.getReader();
const decoder = new TextDecoder();
let text = '';
let received = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
received += value.length;
console.log(`Received ${received} bytes`);
text += decoder.decode(value, { stream: true });
}
text += decoder.decode(); // flush any bytes still buffered
return text;
}This example still collects the whole text in the end, so it doesn't save memory. What it adds is visibility: you know how many bytes have arrived at every step. The sections below build on this loop.
The diagram shows a point that is easy to miss: the fetch() Promise resolves as soon as the headers arrive, not the body. Reading the body is a separate, later phase. That is why you can check response.ok and Content-Length before downloading a single byte of content.
Why TextDecoder needs stream: true
Text in UTF-8 uses one to four bytes per character. A chunk boundary can fall in the middle of a character, for example after the first two bytes of a three-byte "€". If you decode each chunk on its own, that split character turns into replacement characters (�).
Passing { stream: true } tells the decoder to hold back an incomplete trailing sequence and combine it with the start of the next chunk. The final decoder.decode() call with no arguments flushes anything left over. If you skip it, a body that ends in a truncated sequence can lose its last character silently.
Reporting Download Progress
To show a percentage you need the total size. Servers often send it in the Content-Length header.
async function downloadWithProgress(url, onProgress) {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const lengthHeader = response.headers.get('content-length');
const total = lengthHeader ? Number(lengthHeader) : null;
const reader = response.body.getReader();
const chunks = [];
let received = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
received += value.length;
onProgress({ received, total, percent: total ? Math.min(100, (received / total) * 100) : null });
}
return new Blob(chunks, { type: response.headers.get('content-type') ?? '' });
}
downloadWithProgress('https://example.com/big-file.zip', ({ received, percent }) => {
console.log(percent === null ? `${received} bytes` : `${percent.toFixed(1)}%`);
}).then((blob) => console.log('Done:', blob.size, 'bytes'));Storing chunks in an array and passing them to new Blob(chunks) at the end avoids copying data repeatedly. You get the same result as response.blob(), plus progress events.
Gotchas with Content-Length
- The header may be missing. Responses sent with chunked transfer encoding, and many dynamically generated responses, have no
Content-Length. Your UI then needs an indeterminate state, such as a spinner or a running byte count. That is why the code allowstotalto benull. - Compression breaks the math. If the server sends
Content-Encoding: gzip,Content-Lengthis the compressed size, but the browser hands you decompressed bytes.receivedcan then passtotalby a wide margin. TheMath.min(100, ...)caps the display, but the percentage is still wrong. For accurate progress on compressed responses, have the server send the uncompressed size in a custom header and expose it withAccess-Control-Expose-Headersif the request is cross-origin. - Uploads are different.
fetchhas no upload progress event. Request-body streaming exists in some browsers but is not widely usable yet, soXMLHttpRequest'supload.onprogressis still the practical choice for upload progress bars.
Processing Data Before It Finishes Arriving
The bigger win from streaming is acting on data early. Many APIs send NDJSON (newline-delimited JSON): one JSON object per line. With a stream you can parse and display each record the moment its line is complete.
There are two problems to solve. Bytes must become text, and text must be split on newlines even when a line spans two chunks. pipeThrough(new TextDecoderStream()) solves the first problem. It turns the byte stream into a stream of strings and handles split characters for you. For the second problem, you keep the unfinished final line in a buffer.
An async generator (async function*) is a function that can yield values over time. The caller consumes them with for await...of. That fits streaming well:
async function* readLines(response) {
const reader = response.body
.pipeThrough(new TextDecoderStream())
.getReader();
let buffer = '';
let finished = false;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += value;
const lines = buffer.split('\n');
buffer = lines.pop(); // last piece may be an incomplete line
for (const line of lines) {
if (line.trim()) yield line;
}
}
if (buffer.trim()) yield buffer;
finished = true;
} finally {
if (!finished) {
// Consumer stopped early or an error occurred: stop the download.
await reader.cancel().catch(() => {});
}
}
}
async function showEvents(url) {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
for await (const line of readLines(response)) {
const event = JSON.parse(line);
console.log('Event:', event);
if (event.type === 'complete') break; // triggers the finally block above
}
}Look at the finally block. When the consumer breaks out of for await, JavaScript calls the generator's return(), which runs finally. Without the reader.cancel() call, the browser would keep downloading a body nobody will read. The .catch(() => {}) covers the case where the stream has already errored. Cancelling an errored stream rejects, and that rejection would otherwise replace the original error.
Locks, bodyUsed, and Other Single-Use Rules
A stream can have only one active reader at a time. Calling getReader() locks the stream, and the following rules apply:
response.body.lockedbecomestrue.- A second
getReader()call throws aTypeError. response.json(),text(), and the rest reject with aTypeError, because they need their own reader.- Once you start reading,
response.bodyUsedistrue, andresponse.clone()throws.
If you need the stream and a convenience method, call response.clone() before getting a reader. Be careful, though. Both copies share the underlying data, and if you read one much faster than the other, the browser buffers the difference in memory. For a huge download, that buffering wipes out the memory benefit of streaming.
reader.releaseLock() unlocks the stream without cancelling it, so another reader can take over. You rarely need it. reader.cancel() is what you want when you are finished early.
Cancelling and Mid-Stream Errors
You have two ways to stop a streaming download:
reader.cancel()from inside your reading code, as in the generator above.- An
AbortSignalpassed tofetch. Aborting after the headers have arrived makes the pendingreader.read()reject with anAbortError.
const controller = new AbortController();
setTimeout(() => controller.abort(), 2000);
try {
const response = await fetch('https://example.com/huge.log', { signal: controller.signal });
const reader = response.body.getReader();
let bytes = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
bytes += value.length;
}
console.log('Finished:', bytes);
} catch (err) {
console.log(err.name); // 'AbortError' if cancelled during download
}AbortSignal.timeout(ms) covers the whole request, body included. A 10-second timeout will kill a download that is going fine but needs 30 seconds. For long streams, a better pattern is often an "idle" timeout: restart a timer on every chunk and abort only when no data has arrived for a while.
The network can also fail after a 200 OK with half the body already delivered. In that case reader.read() rejects, usually with a TypeError. Code that relies on response.ok alone can't catch this. Wrap the read loop itself in try/catch and decide whether partial data is usable or must be thrown away.
Async Iteration Directly on response.body
The streams specification lets you write for await (const chunk of response.body) without creating a reader yourself. Firefox and Chromium-based browsers support it, and so do Node.js and Deno, but support is not universal across all browsers. If you target every browser, use getReader() as shown in this chapter, or check Symbol.asyncIterator in ReadableStream.prototype first.
When Not to Stream
Streaming adds code and new ways to fail. Use json() or blob() when the response is small, when you need all of it before doing anything (a single large JSON document can't be parsed in pieces with JSON.parse), or when progress doesn't matter. Stream when the body is large, when users benefit from early or partial results, or when the server sends a format designed for incremental parsing, such as NDJSON or Server-Sent-Events-style text.
Exercise
A teammate's progress bar for a file download jumps past 100% and stays there for the last third of the download. The server sends the file with gzip compression. What is the cause, and what are two ways to fix it?
Show answer
Content-Length gives the compressed byte count, but reader.read() delivers decompressed bytes, so the received count grows larger than the total. Fixes: have the server send the uncompressed size in a custom header (and list it in Access-Control-Expose-Headers for cross-origin requests), or serve the file without Content-Encoding so the two numbers match. Capping the value at 100 only hides the symptom.
Exercise
This code throws "TypeError: body stream already read" (the exact wording varies by browser). Why, and how do you fix it while keeping both values? const reader = response.body.getReader(); const first = await reader.read(); const data = await response.json();
Show answer
getReader() locks the stream and read() consumes data, so json() cannot get its own reader. Call response.clone() before getReader() and call json() on the clone, or decode all the chunks yourself and run JSON.parse on the combined text.
Exercise
In the readLines generator, why is the result of buffer.split('\n') handled with lines.pop() instead of yielding every element?
Show answer
A chunk can end in the middle of a line. The last element after splitting may be an incomplete line, so it stays in the buffer and gets joined with the next chunk. Only lines followed by a newline are known to be complete. After the stream ends, whatever is left in the buffer is yielded as the final line.