Mental model
Streaming Markdown is a consistency problem between append-only text deltas and syntax whose meaning can depend on later input. Preserve raw source and parser state, keep an undecided tail, and expose provisional output as provisional. At completion, parse the full document and reconcile it; early rendering is a preview, never the canonical document.
Theory
Markdown is not a sequence of independent characters that can always be turned into final HTML as they arrive. A backtick can start a code span or fence that closes much later. A list item can continue across indented lines. A link label may remain unresolved until a reference definition appears elsewhere in the document. Micromark exposes a stream interface for consuming bytes, but its documentation also explains that reference definitions make a fully streaming interpretation impossible in the general case. A streaming UI therefore needs an explicit policy for uncertain syntax instead of assuming that network chunk boundaries are Markdown boundaries.
Maintain three distinct values: the accumulated source, parser state for open constructs, and the rendered projection. On each delta, append the bytes exactly as received. A parser that exposes incremental tokens can publish nodes it declares stable and retain the unresolved tail. If the chosen parser does not expose that state, parse a coalesced prefix for a clearly provisional preview, then run a complete parse at finish. The final full parse is the source of truth, especially for reference links, tables, and any renderer that replaces the current DOM.
There is a measurable cost to reparsing every growing prefix. Let be the accumulated source length in bytes after update , and the number of updates. Re-reading every prefix costs ; a one-pass parser reads roughly bytes, plus its grammar-specific state updates. With a 48 KiB answer delivered in 48 chunks of 1 KiB, full-prefix parsing reads KiB, or 24.5 times the final source size. This is parser input work only; DOM construction, sanitization, and layout add separate costs.
A coalesced preview
When an incremental AST is unavailable, coalesce deltas to one render per animation frame instead of running a full parser for every network event. This example produces a sanitized preview from the current prefix and marks the host busy until the complete response is reparsed. Partial emphasis or a link may change appearance as new text arrives; consumers should not treat that preview as final content.
typescriptimport { micromark } from "micromark";import DOMPurify from "dompurify";export class MarkdownPreview {private source = "";private frame = 0;constructor(private readonly host: HTMLElement) {host.setAttribute("aria-busy", "true");}append(delta: string): void {this.source += delta;if (this.frame !== 0) return;this.frame = requestAnimationFrame(() => this.renderPreview());}finish(): void {if (this.frame !== 0) cancelAnimationFrame(this.frame);this.frame = 0;this.host.innerHTML = DOMPurify.sanitize(micromark(this.source));this.host.setAttribute("aria-busy", "false");}private renderPreview(): void {this.frame = 0;this.host.innerHTML = DOMPurify.sanitize(micromark(this.source));}}
This full-prefix example is intentionally simple, not an incremental parser. For large responses, keep a stable rendered prefix and reparse only the tail if the parser exposes enough state to prove that the prefix cannot be changed by later definitions. Otherwise, leave ambiguous constructs as plain text or defer rich rendering until the closing delimiter or end marker arrives. When an abort occurs, cancel the scheduled frame and make the partial response state explicit; do not silently relabel an incomplete code fence as complete.
Failure modes and misconceptions
| Failure | Why it happens | Safer behavior |
|---|---|---|
| A fenced block closes only after several deltas | The opening delimiter changes the grammar of every later line until a matching fence | Preserve the open-fence state and do not commit its contents as ordinary paragraphs |
| A reference-style link changes after earlier text was rendered | A definition later in the document can resolve an earlier label | Reconcile the full document at completion or keep such links provisional |
| A parser runs once per tiny token | Growing prefixes repeat work and may exceed the generation rate | Coalesce to a frame or use a genuinely incremental parser interface |
| Raw HTML from model output reaches innerHTML | Markdown parsing does not itself authorize untrusted HTML | Sanitize the produced HTML and apply the application’s link policy |
| Replacing the entire preview jumps the page | Full DOM replacement changes element heights and scroll anchoring | Preserve keyed block nodes and apply an explicit scroll-follow policy |
A line break can be useful as a display hint, but it is not proof that Markdown meaning is settled. GFM tables, indented lists, block quotes, and reference definitions can all depend on material outside the latest line. Use the parser’s grammar, not a collection of ad hoc string checks, to decide what can be committed. For accessible output, keep document order stable and avoid announcing every provisional reparse through a live region; pair the stream with a concise status message instead.
Trade-offs
Parsing the full prefix keeps implementation small and works well for short answers, but the cost grows with both response length and update count. A stable-prefix renderer reduces repeated parsing and layout changes, but it must track open constructs correctly and still handle references that can resolve later. Plain-text streaming is the most robust fallback when a parser cannot expose enough state. Rich formatting can be applied at finish, or to a bounded tail after a server sends explicit block boundaries.
The text stream protocol supplies deltas; it does not specify how Markdown should be rendered. Keep transport framing, Markdown parsing, HTML sanitization, and UI reconciliation as separate steps. That separation lets a team switch from a full-prefix preview to an incremental parser without changing how it validates stream ordering or how it treats the final response.
Decision scenario
A response contains a reference link near its first paragraph, while its reference definition is emitted at the very end. The current preview initially shows the label as plain text and the team wants a stable interface on long answers. Keep the early content provisional or plain text, then parse and reconcile the whole response at the finish marker. Do not permanently commit an unresolved reference as a dead link just because its closing definition has not arrived yet.
Learning outcomes
- Explain why a Markdown parser that accepts input chunks may still need document-wide context to resolve references.
- Estimate repeated parser input when a renderer reparses every prefix.
- Choose between provisional previews, stable parser events, and final-only rich rendering based on latency and grammar requirements.