跪拜 Guibai
← Back to the summary

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

Title: "From 'Can Write' to 'Actually Understand': 20 Lines of SSE Streaming Code and 7 Pitfalls" Author: Xeni

I have written streaming output more than once. It wasn't until I closed the code and retold it in my own words that I realized I couldn't explain why the buffer must exist, what the two stream: true flags each control, or what [DONE] actually does. This post breaks down the 20 lines of core code and records the full journey from "can write" to "actually understand".

1. Look at the Full Chain First

From clicking the button to characters popping onto the screen, the chain goes like this:

Request carries stream: true
  → Server pushes while generating
  → reader.read() reads a chunk at a time (water tap)
  → TextDecoder turns bytes into strings
  → Stored into buffer (temporary pool)
  → split('\n') cuts by line; the possibly-incomplete trailing half-line is fished out with pop() and put back into the buffer
  → For each complete line: filter out those starting with data:, skip [DONE]
  → JSON.parse unwraps; get choices[0].delta.content
  → output.value += delta   ← the direct reason characters pop out
  → Vue reactive re-render
  → while repeats the whole set of actions until done = true

The whole piece of code revolves around two things: fragments (the data the network sends comes in irregularly) and increments (only a few characters are added each time).

2. 20 Lines of Code, Split into Four Sections

The core code from a real project (Vue3 + native fetch, zero dependencies):

① The switch: stream: true

body: JSON.stringify({
  model: model.value,
  stream: true,   // ← tells the server not to hold back; push while generating
  messages: [...]
})

Delete it and the server waits until the entire answer is generated and returns it all at once; the user has to stare at a blank screen for ten-plus seconds.

② Three tools: reader / decoder / buffer

const reader = res.body.getReader()   // holds the water tap handle; reads one chunk at a time
const decoder = new TextDecoder()     // bytes → string
let buffer = ''                        // temporary pool; the most critical piece

getReader() reads the stream chunk by chunk, TextDecoder translates binary into text, and buffer is the soul of the whole piece of code.

③ The accumulation loop: split + pop

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() || ''

Here's a counterintuitive fact: the chunks the network sends do not line up with "one line of message" at all — a single chunk can contain half a line, one line, one and a half lines, or three lines. But the SSE protocol requires every message to occupy one complete line (data: {...}).

An analogy: AI talks like toothpaste being squeezed out, a blob at a time, but you can't control whether each blob happens to be exactly one full message. So a plate (buffer) has to catch it, wait until a complete line accumulates, and leave the unfinished half-line for the next blob.

Why pop() and not shift()? After split('\n'), the segments that got broken off by a newline are the complete ones; the trailing segment has no \n at the end, so it's the one that might be a half-sentence. Whatever needs to be kept is necessarily at the tail. shift() fishes from the head — which is exactly the complete lines — the direction is wrong. (Also, pop is O(1), while shift has to move the whole array.)

④ Extracting characters: data: / [DONE] / delta.content

for (const line of lines) {
  const trimmed = line.trim()
  if (!trimmed.startsWith('data:')) continue   // skip non-data lines
  const data = trimmed.slice(5).trim()
  if (data === '[DONE]') continue               // end-of-generation signal; also skipped
  try {
    const json = JSON.parse(data)
    const delta = json.choices?.[0]?.delta?.content || ''
    output.value += delta
  } catch { /* ignore non-JSON heartbeat lines */ }
}

3. The 7 Real Pitfalls

Every one of these I got wrong and then fixed myself. If you're learning streaming output too, reading this list once is more useful than reading three more tutorials.

# What I thought What's actually true
1 The content is complete when I get [DONE] [DONE] is skipped outright; what makes the loop exit is done: true that reader.read() returns
2 The while loop is the final "output" step The while loop wraps everything from start to finish; it's the "repeat" vehicle for the whole set of actions
3 "Unwrap then concatenate" (couldn't say what was being concatenated) What's being concatenated is delta.content — the few characters added this time
4 pop() "throws away" the half-sentence (discards it) It fishes it out and puts it back into the buffer for temporary storage, to be completed with the next batch — nothing is discarded
5 Couldn't justify why pop A half-sentence is always at the tail (no \n at the end), so pop is the only option
6 decode(value, { stream: true }) is a streaming switch It's insurance for "stitching multi-byte characters across chunks"; it has nothing to do with streaming
7 On a disconnect, "the error callback returns done" read() throws an exception (a Promise rejection) that the outer catch catches; done: true only appears when the server closes the stream normally

Point 6 deserves more explanation: there are two stream: true in the code, with the same name but completely different jobs —

Pure English is single-byte, so a cut can't break it, and removing the second parameter won't garble anything. But Chinese and emoji are multi-byte: remove it and it really garbles. Keeping it is the correct way to write it.

One extra detail: characters already shown when the network drops don't get lost — each chunk renders as it arrives; a disconnect only affects the content after it.

4. How to Confirm You Actually Understand: The Four-Layer Verification Method

This section has nothing to do with SSE, but it's worth more than SSE itself.

My old way of checking whether I "understood" was to read it again, and after reading I felt I understood everything — this is the familiarity trap: repeated exposure produces an illusion of mastery; it's really just being familiar with the look.

The genuinely effective test is to close the material and actively retrieve it:

  1. Can retell — close the code and describe the full flow in your own words;
  2. Can explain — answer "why". This layer exposes fake understanding best: why must the buffer exist? Why pop instead of shift? What happens if you remove stream: true?
  3. Can adapt — still recognize it in a different scenario. Does pure English still need decode's stream parameter? When does done become true on a disconnect? Can you write SSE data yourself that the code can parse?
  4. Can teach — explain it to someone else and let them poke at where you're vague.

The hardest layer is "can predict the outcome": change a piece of data, predict what output will become, then run it and see whether it matches. If it matches, you're not memorizing a procedure — you actually understand the mechanism.

Appendix: Self-test Questions

Don't look at the answers above first; try these:

  1. Without looking at the code, walk through the full chain from "clicking the button" to "characters pop out".
  2. Why must the buffer exist? Why use pop() instead of shift()?
  3. What do the two stream: true in the code each control?
  4. What happens on a disconnect? Do the already-shown characters get lost?
  5. Write a piece of SSE data yourself that the code can parse and output "。" (a Chinese period).

The question you can't answer is the place you haven't truly digested — go back and re-chisel it.


Project: Vue3 + Vite; the frontend connects directly to the AI Gateway; zero backend. 2026-11-24.

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

去吧波波鸟

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