Streaming Large JSON Responses to the Browser
Reading a big JSON payload incrementally with ReadableStream so the first rows arrive before the last byte does.
- Performance
- Streaming
- Fetch
- Memory
A dashboard that fetches a 40 MB JSON array has two problems: the user waits for the whole body, and the browser holds a second copy in memory while parsing. Streaming lets the first rows paint while the rest is still on the wire.
Start with the fetch body
response.body is a ReadableStream<Uint8Array>. Wrapping it in a TextDecoderStream and then a line reader gives you NDJSON rows as they arrive. The server has to emit newline-delimited records rather than one giant object.
async function* lines(res: Response): AsyncGenerator<string> {
const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();
let buffer = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += value;
const parts = buffer.split('\n');
buffer = parts.pop() ?? '';
for (const part of parts) if (part) yield part;
}
if (buffer) yield buffer;
}
Render in batches, not per record
Yielding a row does not mean every row should touch the DOM. Accumulate 100 records and flush once per animation frame. The stream stays responsive and layout happens at frame cadence instead of at network cadence.
Handle a broken stream honestly
Connections drop. Keep the rows already rendered, expose a retry affordance, and remember the cursor so a retry resumes instead of restarting. A visible partial result with a clear “reconnecting” state beats an empty screen.
Know when streaming is overkill
If the payload is 200 KB, the parsing complexity costs more than the latency it saves. Reach for streaming when time-to-first-row matters and the data is genuinely large or unbounded.