Summary
Read response.body reader incrementally — parse NDJSON/SSE/chunked HTML as bytes arrive. Buffer until complete loses TTFB benefits. Handle partial JSON and connection drops. Server must send correct Content-Type and disable buffering (nginx X-Accel-Buffering).
Code example
const response = await fetch('/api/stream');
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() ?? '';
lines.forEach(parseLine);
}
Key points
- Read
response.bodyreader incrementally — parse NDJSON/SSE/chunked HTML as bytes arrive. - Buffer until complete loses TTFB benefits.
- Handle partial JSON and connection drops.
- Server must send correct
Content-Typeand disable buffering (nginxX-Accel-Buffering).