Skip to main content
Back to Community & Earn Hub

The annoying bug where your chat widget renders half a markdown code block during SSE streaming

@devon_brooks2 days ago·1 min read 2210 views
The annoying bug where your chat widget renders half a markdown code block during SSE streaming

Anyone who has built a streaming AI chat UI has run into this at some point. Everything looks great in local testing, and then in production:

  1. The model outputs an opening ```python fence, and for the next 4 seconds the syntax highlighter flashes between plain text and broken DOM nodes on every incoming token.
  2. On a shaky mobile connection, EventSource reconnects mid-response and either loses the last 20 tokens or replays from the start because there wasn't a stream cursor.

Keep markdown stable while tokens arrive

Re-parsing the entire message string from character 0 on every token gets noticeably laggy once a response passes 300 lines. Two simple habits fixed both the flicker and CPU spikes for us:

  • Split completed blocks from the active tail: Once a paragraph or fenced code block has a closing \n\n or closing ```, memoize it so React never re-parses finished blocks.
  • Auto-close dangling fences in a tiny pre-pass before handing the active tail to your markdown renderer so half-streamed code stays inside a <pre> box instead of spilling into prose.
ts
export function closeOpenCodeFence(partial: string): string {
  const fenceMatches = partial.match(/```/g);
  if (fenceMatches && fenceMatches.length % 2 === 1) {
    return partial + "\n```";
  }
  return partial;
}

For reconnects, push each SSE chunk into a short-lived Redis stream (XADD) with a monotonic event id: so Last-Event-ID lets the client pick up right where the socket dropped.

2 Comments

Discussion

@chloe_martinez2 days ago

Auto-closing dangling triple backticks in the streaming tail + memoizing finished blocks saved our React CPU usage on long code answers.

@aditya_verma2 days ago

XADD in Redis with Last-Event-ID is also super clean if users switch tabs or lock their phone mid-stream.

Join the developer discussion

Sign in or create a free account to comment (+10 pts) and tag helpful AIStoreHub repositories.