跪拜 Guibai
← All articles
Frontend

SSE Streaming in 20 Lines: The 7 Misconceptions That Separate Copying From Comprehension

By Xeni ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

SSE streaming breaks in ways that only surface under real conditions, and the misconceptions above are exactly where the breakages happen: a chunk splits a multi-byte character, a disconnect drops mid-stream, the buffer silently corrupts output. Knowing which flag controls what and where the loop really exits determines whether those failures take minutes or hours to debug.

Summary

SSE streaming from a Vue3 frontend works as a chain: the request body carries stream: true, the server pushes partial text as it generates, reader.read() pulls chunks one at a time, TextDecoder converts bytes, buffer holds incomplete data, split('\n') cuts full lines, and JSON.parse extracts choices[0].delta.content, which accumulates into output.value and triggers a Vue re-render. That re-render is the literal cause of the typewriter effect.

The entire mechanism exists to handle two facts. Network chunks never arrive aligned with SSE's requirement that each message occupy one complete line ending in a newline, and the server sends only incremental new characters per event, never the whole answer. Buffer exists as a temporary pool that catches the trailing half-line after split, and pop() is the only correct retrieval because the incomplete segment always sits at the tail. shift() would grab complete lines from the front and cost O(n) array movement.

Seven pitfalls read as a confession list. [DONE] gets skipped as a content line while the loop actually exits on reader.read() resolving done: true. The while loop wraps the whole cycle; it isn't the output step. The two stream: true flags do unrelated jobs, one telling the server to push and the other telling TextDecoder to stitch multi-byte characters split across chunks, a difference that breaking Chinese or emoji output exposes. Disconnects throw a Promise rejection rather than a done flag, and already-rendered text survives them. A four-layer verification method closes things out: retell, explain why, adapt to a new scenario, and predict output before running.

Takeaways
— Network chunks arrive misaligned with SSE message boundaries; buffer stores the trailing partial segment after split('\n') until the next chunk completes it.
— pop() retrieves the incomplete tail and returns it to buffer; shift() would pull complete lines from the front and cost O(n) array movement.
— The request body's stream: true tells the server to push partial output; TextDecoder's stream: true tells it to temporarily hold multi-byte characters split across chunk boundaries and stitch them with the next chunk.
— [DONE] is skipped along with other non-content data lines; the while loop terminates when reader.read() resolves with done: true.
— New characters arrive in choices[0].delta.content; delta means the incremental addition since the last event, not a full answer.
— output.value += delta triggers Vue's reactive re-render, which is the direct mechanism behind the typewriter effect.
— On a network disconnect, reader.read() throws a Promise rejection that the outer catch handles; done: true only appears when the server closes the stream normally.
— Removing the stream flag from TextDecoder breaks Chinese and emoji output because multi-byte characters get cut mid-sequence; plain ASCII English survives without it.
— Characters already rendered stay on screen during a disconnect; only subsequent content is affected.
Conclusions

Shared identifiers across API layers make shallow reading actively misleading: two stream: true flags do unrelated work, yet the identical name guarantees developers conflate them until a multi-byte corruption forces the issue.

The [DONE] mix-up generalizes to streaming APIs beyond this stack: protocol sentinels are conventions the tools define, but the real exit condition lives in the transport layer, and developers who conflate them misdiagnose stream termination.

Output prediction is a stronger comprehension check than any written test: changing one input, forecasting the rendered result, and comparing against the run isolates mechanism gaps that explanations conceal.

Misconceptions surface only at failure time: the seven items above all appear on disconnects, multi-byte boundaries, and protocol edge cases that tutorials don't exercise, so unexamined streaming code works precisely until it breaks.

Concepts & terms
SSE (Server-Sent Events)
A protocol where the server pushes text lines over a single HTTP connection; each event is a line prefixed with data: and must end with a newline.
Buffer (in SSE parsing)
A temporary string that accumulates raw decoded chunks until a complete line ending in '\n' appears, keeping the trailing half-line for the next batch.
[DONE]
The final SSE message some AI APIs send to mark the end of generation; it carries no content and is skipped, not parsed as JSON.
delta.content
The incremental fragment of new text in an OpenAI-style streaming chat completion; each event carries only the newly generated characters, and accumulating them rebuilds the full answer.
TextDecoder with { stream: true }
A decoding option that buffers a multi-byte character split across chunk boundaries and stitches it with the next chunk, preventing garbled output for CJK or emoji.
reader.read()
A ReadableStream method returning a Promise for {done, value}; done: true signals a normal stream close, while transport errors arrive as Promise rejections rather than done flags.
From the discussion
Featured comments
去吧波波鸟

Too right, the part about the two stream:true is the key. That skin-deep pretense gets torn off harshly.

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗