Skip to content
mentoor

Topic 1 of 4 · 4 min read

Streaming tokens into the page

Goal: Render a streamed answer, including markdown and code blocks, into the page without layout jumps, flicker or broken formatting.

Treat a streamed answer as text that grows, and render it in small, batched, stable steps: read chunks, append to state, parse markdown on the whole string, and keep the layout from moving. The model sends pieces; the page decides how often and how safely to paint them.

Check yourself · 1 of 3

A streamed reply contains an accented character whose bytes are split across two network chunks. What prevents it from showing as a broken symbol?

Choose one answer

Why it matters

Streaming is what makes a ten-second answer feel alive. Done badly it flickers, jumps the scroll position, shows half-formed markdown such as a lone ** or an open code fence, and burns CPU by re-rendering on every token. Users read while it streams, so any jump costs them their place.

How to do it

  1. Read the body as a stream. fetch gives response.body.getReader(). Decode with one TextDecoder and pass { stream: true } so a multi-byte character split across chunks is not corrupted. If the server sends server-sent events, split on blank lines and keep the unfinished tail for the next chunk.
  2. Accumulate, do not append DOM nodes. Keep one string in state. Re-render the message from that string.
  3. Batch paints. Tokens can arrive faster than the screen refreshes. Write them to a buffer and flush once per animation frame with requestAnimationFrame.
  4. Parse markdown on the full text each flush. Parsing only the new chunk breaks lists, tables and fences. If a code fence is still open, close it virtually for display so the block does not swallow the rest of the page.
  5. Stop layout jumps. Give the message container a minimum height, avoid inserting content above the viewport, and auto-scroll only if the user is already near the bottom. If they scrolled up to read, leave them alone.
  6. Escape and sanitize. Model output is untrusted. Render markdown through a sanitizer; never assign it to innerHTML raw.

Before and after

// Weak: one DOM write per chunk, raw HTML, mangled characters
for await (const chunk of stream) {
  el.innerHTML += new TextDecoder().decode(chunk);
  el.scrollIntoView();
}
// Better: one decoder, one string, one paint per frame, sanitized markdown
const decoder = new TextDecoder();
let text = "";
let queued = false;
for await (const chunk of stream) {
  text += decoder.decode(chunk, { stream: true });
  if (!queued) {
    queued = true;
    requestAnimationFrame(() => {
      queued = false;
      el.innerHTML = sanitize(renderMarkdown(closeOpenFence(text)));
      if (nearBottom(scroller)) scroller.scrollTop = scroller.scrollHeight;
    });
  }
}

What goes wrong

  • Chunk boundaries are not token boundaries. A chunk can end mid-word, mid-character or mid-event. Never assume a chunk is a complete unit.
  • Re-rendering the whole history on every token. Memoize finished messages so only the live one updates.
  • Forced scroll. Pulling the user to the bottom while they read earlier text is the most common complaint about streaming UIs.
  • Unsanitized output. A model can echo attacker-controlled text from a document it summarized, including HTML.

Examples

Closing an unfinished fence for display

The stream has delivered a sentence, an opening code fence marked ts, and one line of code, but the closing fence has not arrived. A markdown parser then treats everything after the opening fence as code, including text that comes later. The renderer counts fence markers in the text. If the count is odd, it appends a closing marker to a copy used only for display. The stored text is unchanged, so the real closing fence still lands correctly when it arrives.

Reading an event stream safely

const reader = res.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 events = buffer.split("\n\n");
  buffer = events.pop() ?? "";
  for (const e of events) handleEvent(e);
}

The last piece after the final blank line may be half an event, so it stays in the buffer until the next read.

Key points

  • Decode the byte stream with one TextDecoder and the stream option so characters split across chunks stay intact.
  • Keep the answer as one growing string and re-render from it, rather than appending nodes per chunk.
  • Batch updates to one paint per animation frame so fast token bursts do not flicker or freeze the page.
  • Parse markdown from the full text on each flush and close an open code fence for display only.
  • Auto-scroll only when the reader is already at the bottom, and sanitize all model output before it reaches the DOM.

Common mistakes

  • Calling decode without the stream option, which corrupts emoji and non-Latin characters that straddle two chunks.
  • Parsing markdown on each new chunk alone, so lists, tables and code blocks break apart.
  • Scrolling to the bottom on every update, which yanks the page away from a reader who scrolled up.
  • Writing model output to innerHTML without sanitizing it.

Check yourself · 2 of 3

Tokens arrive about 80 times per second and the page stutters. Which change helps most?

Choose one answer

Check yourself · 3 of 3

A user scrolled up to reread an earlier paragraph while a new answer streams in. What should the page do?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic