Dev.Lib
arrow_backBack to Blogs
LEVEL_055.7June 27, 20261 min read

Streaming fetch response handling

Caching & Networking

Read `response.body` reader incrementally — parse NDJSON/SSE/chunked HTML as bytes arrive.

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.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).

Further reading

Related concepts