Sub topic 11
Streaming Large Responses
This chapter assumes you are comfortable with async/await, with checking response.ok, and with the fact that a response body can be read only once. Earlier chapters read bodies with json() or text(), which wait for the whole response before giving you anything. For large downloads, slow servers, or data that arrives over time, you can read the body piece by piece instead.
The Body Is a Stream
response.body is a ReadableStream. A ReadableStream is an object that hands you data in chunks as the data arrives from the network. Each chunk is a Uint8Array of raw bytes. Methods like json() read this same stream to the end for you. When you read it yourself, you can:
- show download progress
- process records before the full response has arrived
- stop early and drop the rest of the response
To read the stream, call getReader(). Each call to reader.read() returns a Promise that resolves to { done, value }. While done is false, value holds the next chunk. When done is true, the stream is finished.
Note that fetch() resolves as soon as the status and headers arrive. The body may still be downloading at that point, and that is why streaming works at all.
Reporting Download Progress
This function collects the chunks, reports progress as they come in, and returns the complete file as a Blob.
async function downloadWithProgress(url, onProgress) {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const total = Number(response.headers.get('content-length')) || 0;
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);
}
return new Blob(chunks);
}
const blob = await downloadWithProgress('https://example.com/video.mp4', (got, total) => {
const pct = total ? Math.round((got / total) * 100) + '%' : `${got} bytes`;
console.log(`Downloaded ${pct}`);
});
console.log('Done:', blob.size);Decoding Text Across Chunk Boundaries
A chunk boundary can fall in the middle of a multi-byte UTF-8 character. If you call new TextDecoder().decode(value) on each chunk separately, you can get garbled characters. You have two fixes. One is to pass { stream: true } to decode() and call decode() once more with no arguments at the end. The other is to pipe the stream through a TextDecoderStream, which takes care of this for you.
The example below reads newline-delimited JSON (NDJSON), a format with one JSON object per line. It handles each record as soon as its line is complete. Lines can also be split across chunks, so the code keeps the unfinished last piece in a buffer.
async function readNdjson(url, onRecord) {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${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;
const lines = buffer.split('\n');
buffer = lines.pop(); // keep the incomplete last line
for (const line of lines) {
if (line.trim()) onRecord(JSON.parse(line));
}
}
if (buffer.trim()) onRecord(JSON.parse(buffer));
}
await readNdjson('https://api.example.com/events.ndjson', (event) => {
console.log('Event:', event);
});Stopping Early and Common Mistakes
If you have what you need, call await reader.cancel(). That discards the rest of the body and closes the connection for this response. An AbortSignal passed to fetch() also works: aborting makes the pending read() reject with an AbortError.
| Mistake | What happens | Fix |
|---|---|---|
| Calling `response.json()` after `getReader()` | TypeError: the stream is locked | Pick one way to read, or `clone()` the response first |
| Decoding each chunk separately | Broken multi-byte characters | Use `{ stream: true }` or `TextDecoderStream` |
| Assuming one chunk is one line or record | `JSON.parse` fails on partial data | Buffer text and split on delimiters |
| Trusting `Content-Length` | Progress goes past 100% or never shows | Treat the total as a hint |
| Using `for await (const chunk of response.body)` everywhere | Fails in browsers without async iteration of streams | Use `getReader()` for the widest support |
Exercise
You stream a UTF-8 text response and call new TextDecoder().decode(value) on each chunk, joining the results. Most of the output looks fine, but an occasional emoji or accented letter shows up as "�". Why does this happen, and what are two ways to fix it?
Show answer
A multi-byte character was split across two chunks, and decoding each half separately produces replacement characters. Fix 1: create one TextDecoder, call decoder.decode(value, { stream: true }) for every chunk, then call decoder.decode() at the end to flush. Fix 2: read from response.body.pipeThrough(new TextDecoderStream()), which yields correctly decoded strings.
Exercise
In downloadWithProgress, the logged percentage reaches 340% for one file. The server sends Content-Encoding: gzip. Explain the cause.
Show answer
Content-Length gives the size of the compressed body, but the browser decompresses the data before passing it to the stream. The received byte count is therefore the decompressed size, which is larger than the total. Treat the total as unreliable when the response is compressed, for example by capping progress at 100% or showing only the bytes received.