❯ehsan.blog
~/blog/consuming-sse-and-ndjson-streams-from-fetch-without-a-library — zsh
❯cat consuming-sse-and-ndjson-streams-from-fetch-without-a-library.md

How to consume SSE and NDJSON streams from fetch without a library

·12 min read

How to consume SSE and NDJSON streams from fetch without a library — article card for a post by Ehsan Shahid

A lot of APIs stream now — chat completions, live prices, progress updates on a long job. The response comes back as text/event-stream (Server-Sent Events) or as newline-delimited JSON (NDJSON), and fetch’s response.body already hands you a ReadableStream<Uint8Array> for either one. The annoying part isn’t getting the stream; it’s turning raw byte chunks into “one event at a time,” correctly, without a library. I did this for api-client’s ctx.stream helper. I want to walk through the real implementation, and then spend most of the post on the one part I got wrong — a cancel that looks like it works, passes review, and quietly does nothing. I only found it because I sat down and measured it.

The primitive underneath everything: iterating lines, correctly

Both SSE and NDJSON are fundamentally line-oriented text formats. So the one function everything else builds on is “give me a byte stream, hand me back one text line at a time”:

ts
export async function* iterateLines(
  stream: ReadableStream<Uint8Array>,
  signal?: AbortSignal,
): AsyncGenerator<string> {
  const reader = stream.getReader();
  const decoder = new TextDecoder();
  let buffer = '';
  try {
    for (;;) {
      if (signal?.aborted) throw abortError();
      const { done, value } = await reader.read();
      if (done) break;
      buffer += decoder.decode(value, { stream: true });
      let idx: number;
      while ((idx = buffer.indexOf('\n')) !== -1) {
        const line = buffer.slice(0, idx).replace(/\r$/, '');
        buffer = buffer.slice(idx + 1);
        yield line;
      }
    }
    buffer += decoder.decode(); // flush any trailing partial multi-byte char
    if (buffer.length > 0) yield buffer.replace(/\r$/, '');
  } finally {
    reader.releaseLock();
  }
}

Two things here are easy to get wrong on a first attempt.

Chunk boundaries don’t respect line boundaries, or even character boundaries. A network chunk can end in the middle of a line — or, if the payload has multi-byte UTF-8 characters, in the middle of a single character. That’s exactly what decoder.decode(value, { stream: true }) is for: passing { stream: true } tells TextDecoder “this might not be the end, hold onto any incomplete trailing bytes and prepend them to the next chunk” instead of emitting a replacement character for a character that’s genuinely just split across two reads. Skip that option and you’ll get garbled text on chunk boundaries that happen to fall mid-character — a bug that’s rare enough in testing to ship, and common enough in production (over a real network, with real chunking) to be reported.

Line splitting has to run in a loop, not an if. A single read() can contain many complete lines, or zero. The while ((idx = buffer.indexOf('\n')) !== -1) loop drains every complete line currently in the buffer before going back to reader.read() for more bytes — an if here would silently process only the first line per chunk and leave the rest sitting in the buffer until the next read happened to trigger another pass, which is a subtle “sometimes-slow, sometimes-wrong-order-feeling” bug rather than a clean crash.

The trailing buffer += decoder.decode() after the loop exits (no { stream: true } this time) does two jobs at once: it flushes any leftover multi-byte character fragment, and it makes sure a stream that ends without a final newline doesn’t lose its last line — plenty of real servers don’t bother sending a trailing \n on the very last chunk.

NDJSON: the easy case once you have iterateLines

Newline-delimited JSON is genuinely just “parse each line as JSON”:

ts
export async function* parseNdjson<T = unknown>(
  stream: ReadableStream<Uint8Array>,
  signal?: AbortSignal,
): AsyncGenerator<T> {
  for await (const line of iterateLines(stream, signal)) {
    const trimmed = line.trim();
    if (trimmed.length === 0) continue; // skip keep-alive blank lines
    yield JSON.parse(trimmed) as T;
  }
}

The only real decision is skipping empty lines rather than trying to JSON.parse('') — some NDJSON producers send a blank line periodically as a connection keep-alive, and treating that as a parse error would kill a perfectly healthy stream.

SSE: a small state machine, not a regex

Server-Sent Events are a field-based, block-oriented format — each event is a run of field: value lines terminated by a blank line — so it needs a tiny bit of state, not just a line transform:

ts
export async function* parseSse(
  stream: ReadableStream<Uint8Array>,
  signal?: AbortSignal,
): AsyncGenerator<SseEvent> {
  let event: string | undefined;
  let id: string | undefined;
  const dataLines: string[] = [];

  const flush = (): SseEvent | undefined => {
    if (dataLines.length === 0 && event === undefined && id === undefined) return undefined;
    const out: SseEvent = { data: dataLines.join('\n') };
    if (event !== undefined) out.event = event;
    if (id !== undefined) out.id = id;
    event = undefined; id = undefined; dataLines.length = 0;
    return out;
  };

  for await (const line of iterateLines(stream, signal)) {
    if (line === '') {
      const ev = flush();
      if (ev && (ev.data.length > 0 || ev.event !== undefined)) yield ev;
      continue;
    }
    if (line.startsWith(':')) continue; // comment line, per spec
    const colon = line.indexOf(':');
    const field = colon === -1 ? line : line.slice(0, colon);
    let value = colon === -1 ? '' : line.slice(colon + 1);
    if (value.startsWith(' ')) value = value.slice(1); // spec: strip one leading space
    if (field === 'event') event = value;
    else if (field === 'data') dataLines.push(value);
    else if (field === 'id') id = value;
    // other fields (`retry`) are ignored — see the note below
  }
  const tail = flush();
  if (tail && (tail.data.length > 0 || tail.event !== undefined)) yield tail;
}

A few spec details that are easy to skip if you’re working from vague memory of “SSE is like server push” rather than the actual format: a line starting with : is a comment and must be ignored outright (some servers use it purely as a heartbeat to keep the connection alive through proxies). Multiple data: lines before a blank line get joined with \n into one event — SSE explicitly allows a multi-line payload this way. And exactly one leading space after the colon is stripped, not all whitespace — data: two spaces keeps its second space.

One honest caveat on that last branch: retry is not an unknown field. It is a real part of the spec, and it tells the browser’s built-in EventSource how long to wait before reconnecting. We ignore it here because this parser never reconnects — one fetch, one stream, and the caller decides what to do when it ends. That is a fair trade, but it is a choice, not spec compliance. If you later add auto-reconnect, retry is the first field you have to start reading.

The last line — flushing whatever’s left in dataLines/event/id after the loop exits — matters for the same reason the trailing buffer flush in iterateLines matters: a server can close the stream right after the last event’s fields, without sending the final blank-line terminator, and without that flush you’d silently drop the very last event.

The cancel button that does nothing

Here is the version of this I believed for a long time, and the version that is sitting in api-client today. Every generator checks the abort signal on each turn of the loop, right before it reads:

ts
for (;;) {
  if (signal?.aborted) throw abortError();
  const { done, value } = await reader.read();
  ...
}

That looks like cancellation. It reads like cancellation. I would have nodded it through in a code review.

It does not cancel anything.

Look at the order of operations. The check runs, it passes, and then await reader.read() parks. If the user hits cancel one millisecond later, there is nobody left to notice. The check already happened. The code is now sitting inside a promise that only settles when the server sends more bytes — and a stalled stream is exactly the case where the server never does. So the one situation you wrote the cancel for is the one situation it cannot help with.

I did not want to argue about this from memory, so I measured it. A stream that sends one chunk and then goes quiet forever, with an abort fired at 100ms:

text
abort fired at 100ms, still running at 1000ms => never stopped

It never stops. Not at one second, not ever. The for await loop just hangs, holding the connection open, while the UI shows a spinner that the user already asked you to cancel.

Why it still seems to work in real apps

If you have shipped this exact code and never had a complaint, you are not imagining it. It usually does work — for a reason that has nothing to do with the check in the loop.

When you pass the same signal to fetch itself, aborting it tears down the HTTP request underneath you. That makes the response body stream error out, and that is what wakes up the parked reader.read(). Same stalled server, same 100ms abort, the only difference being where the signal is handed in:

text
signal passed to fetch      => AbortError after 137ms
signal only given to parser => still hung at 1200ms

So fetch was doing the cancelling the whole time. The loop check was taking the credit.

That distinction is not academic. The moment the stream comes from anywhere other than the fetch call you control — a body you were handed, a stream from a worker, a test double, a ReadableStream you built yourself — the free cancellation disappears, and all you are left with is a check that cannot fire. Nothing changes in your parser. It just quietly stops being cancellable.

Making the parser cancel on its own

The fix is to stop asking whether the signal fired and start listening for it. When it fires, cancel the reader. Cancelling the reader settles the read that is currently parked, which is the whole problem:

ts
export async function* iterateLines(
  stream: ReadableStream<Uint8Array>,
  signal?: AbortSignal,
): AsyncGenerator<string> {
  const reader = stream.getReader();
  const decoder = new TextDecoder();
  let buffer = '';

  const onAbort = () => void reader.cancel(signal?.reason).catch(() => {});
  if (signal) {
    if (signal.aborted) onAbort();
    else signal.addEventListener('abort', onAbort, { once: true });
  }

  try {
    for (;;) {
      const { done, value } = await reader.read();
      if (done) break;
      buffer += decoder.decode(value, { stream: true });
      let idx: number;
      while ((idx = buffer.indexOf('\n')) !== -1) {
        const line = buffer.slice(0, idx).replace(/\r$/, '');
        buffer = buffer.slice(idx + 1);
        yield line;
      }
    }
    signal?.throwIfAborted();
    buffer += decoder.decode();
    if (buffer.length > 0) yield buffer.replace(/\r$/, '');
  } finally {
    signal?.removeEventListener('abort', onAbort);
    void reader.cancel().catch(() => {});
  }
}

Same stalled stream, same abort at 100ms, no signal given to fetch at all:

text
AbortError after 100ms

On the dot, because the abort event does the work instead of waiting for a chunk that is never coming.

Three small details in there are worth naming, because each one is a bug if you skip it:

  • if (signal.aborted) onAbort() before subscribing. A signal can already be aborted by the time you get here. addEventListener on an event that has come and gone never fires, so without this line an already-cancelled request would stream happily to the end.
  • throwIfAborted() after the loop. Cancelling the reader makes the loop exit normally, as though the stream simply finished. Without this, a cancelled stream would look to the caller like a complete one — a truncated response silently reported as success, which is worse than an error.
  • reader.cancel() in finally, not releaseLock(). This one surprised me. releaseLock() unlocks the stream but never tells it to stop, so when a caller does break out of the for await early, the connection stays open with nobody reading it. I measured both: with releaseLock(), the stream’s cancel hook was never called after an early break; with reader.cancel(), it fires every time. If your users can close a panel mid-stream, that is the difference between releasing the connection and leaking one per click.

And the loop check I just spent six paragraphs criticising — it is not worthless, it is just oversold. It catches an abort that lands between reads, while your own code is busy handling the lines it already has. That is a genuine, narrow win. It is simply not the thing standing between your users and a stuck spinner, and labelling it “cancellation” stopped me from looking for the thing that was.

What a caller actually does with this

None of this is useful in the abstract — it exists so a module method can look like a normal async iterator to whoever calls it, regardless of which wire format the server actually used:

ts
chat: async (ctx, prompt: string) => {
  for await (const chunk of ctx.stream<{ token: string }>(
    { method: 'POST', path: '/chat', body: { prompt } },
    { mode: 'ndjson' },
  )) {
    process.stdout.write(chunk.token);
  }
};

The caller writes a plain for await loop and never touches ReadableStream, TextDecoder, or any of the parsing details above directly — ctx.stream picks parseNdjson or parseSse based on the mode option and hands back one already-typed object per iteration. That’s the payoff for getting the low-level pieces right: chunk boundaries, multi-line SSE blocks and cancellation all stay in one small file that gets written once and tested once, instead of being re-derived badly at every call site.

The takeaway

iterateLines, parseNdjson and parseSse come to roughly a hundred lines between them, and none of it needs a dependency. What it needs is care in the three places a five-minute demo never reaches: a chunk that ends mid-character, a stream that ends without its final newline or blank line, and a cancel that has to interrupt a read already in flight.

That last one is the reason I rewrote this post instead of publishing the draft I had. The code I shipped checked an abort signal in the obvious place, and I never questioned it, because in the app it appeared to work — fetch was quietly covering for it. Checking a flag before you block is not cancellation. If you take one thing from here, make it the habit of proving the cancel, not reading it: start a stream, stall the server, hit abort, and watch the clock. Mine ran for a full second after the user gave up. Yours might still be running.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.