How Broken UTF-8 Multibyte Characters Happen in SSE Stream Readers
In UTF-8, characters are encoded using 1 to 4 bytes: ASCII characters take 1 byte (0xxxxxxx), while accented Latin characters, emojis, or non-Latin scripts (such as Urdu, Arabic, CJK) take 2 to 4 bytes where leading bytes start with 110xxxxx, 1110xxxx, or 11110xxx and continuation bytes start with 10xxxxxx. In a Server-Sent Events (SSE) stream, TCP packets and chunked HTTP reads split bytes at arbitrary network boundaries—so a 3- or 4-byte character can arrive with its first 1–2 bytes in chunk $N$ and its remaining bytes in chunk $N+1$.
- Premature per-chunk decoding (
Buffer.toString("utf8")orTextDecoderwithout{ stream: true }): Callingchunk.toString("utf8")ornew TextDecoder().decode(chunk)on each raw byte chunk independently decodes incomplete trailing bytes at the end of a chunk into Unicode replacement characters (U+FFFD, ``) instead of waiting for the remaining bytes in the next chunk. - String-level slicing after decoding: Even if decoding succeeds, slicing decoded JavaScript strings by UTF-16 code units rather than complete UTF-8 sequences or SSE event boundaries (
\n\n) can split surrogate pairs (such as emojis outside the Basic Multilingual Plane) or truncatedata:payloads mid-character. - SSE framing + byte boundaries interacting: SSE lines are delimited by
\n(or\r\n), and events are separated by blank lines (\n\n). Splitting raw bytes directly into strings before handling incomplete trailing UTF-8 sequences corrupts both text content and SSE event lines if a multibyte character straddles a chunk split.
Steps to Prevent Broken UTF-8 Characters in an SSE Stream Reader
- Decode bytes incrementally with
TextDecoder(..., { stream: true })orStringDecoder: Use a stateful decoder (new TextDecoder("utf-8", { stream: true })in Web Streams/fetch orStringDecoder("utf8")fromnode:string_decoder) that buffers incomplete trailing multibyte sequences internally until the next chunk supplies the missing bytes. - Buffer SSE lines/events cleanly after stateful decoding: Append decoded text chunks to an event/line buffer and split on
\nor\n\nboundaries, keeping any incomplete trailing event/line in the buffer for the next chunk. - Flush the decoder on stream end (
decoder.decode()): Calldecoder.decode()with no arguments (ordecoder.end()) once the stream closes so any final buffered bytes are flushed cleanly and any genuinely truncated trailing byte sequence at EOF is surfaced or handled explicitly. - Test with split multibyte sequences and multi-chunk SSE frames: Unit-test your SSE parser by feeding byte arrays split at every single byte offset across 2-, 3-, and 4-byte UTF-8 characters (like
é,中,اردو, and🚀).
TypeScript Example: Stateful UTF-8 Decoding in a Fetch SSE Reader
export interface SseEvent {
event: string;
data: string;
}
/**
* Reads an SSE byte stream without splitting UTF-8 multibyte characters across chunks.
* Uses `{ stream: true }` on TextDecoder so partial 2-4 byte sequences wait for
* subsequent bytes before being decoded into strings.
*/
export async function* readSseStream(
body: ReadableStream<Uint8Array>,
signal?: AbortSignal
): AsyncGenerator<SseEvent, void, unknown> {
const reader = body.getReader();
const decoder = new TextDecoder("utf-8", { stream: true });
let buffer = "";
try {
while (true) {
if (signal?.aborted) {
throw new DOMException("SSE stream aborted", "AbortError");
}
const { value, done } = await reader.read();
if (done) {
break;
}
if (value && value.byteLength > 0) {
// `stream: true` holds back incomplete trailing UTF-8 bytes until the next chunk
buffer += decoder.decode(value, { stream: true });
}
// Normalize CRLF to LF for consistent SSE frame parsing
buffer = buffer.replace(/\r\n/g, "\n");
let separatorIndex = buffer.indexOf("\n\n");
while (separatorIndex !== -1) {
const rawEvent = buffer.slice(0, separatorIndex);
buffer = buffer.slice(separatorIndex + 2);
const parsed = parseSseFrame(rawEvent);
if (parsed) {
yield parsed;
}
separatorIndex = buffer.indexOf("\n\n");
}
}
// Flush any remaining buffered bytes at stream completion
buffer += decoder.decode().replace(/\r\n/g, "\n");
if (buffer.trim().length > 0) {
const parsed = parseSseFrame(buffer);
if (parsed) {
yield parsed;
}
}
} finally {
reader.releaseLock();
}
}
function parseSseFrame(rawFrame: string): SseEvent | null {
let eventName = "message";
const dataLines: string[] = [];
for (const line of rawFrame.split("\n")) {
if (!line || line.startsWith(":")) {
continue;
}
const colonIdx = line.indexOf(":");
const field = colonIdx === -1 ? line : line.slice(0, colonIdx);
let value = colonIdx === -1 ? "" : line.slice(colonIdx + 1);
if (value.startsWith(" ")) {
value = value.slice(1);
}
if (field === "event") {
eventName = value || "message";
} else if (field === "data") {
dataLines.push(value);
}
}
if (dataLines.length === 0) {
return null;
}
return {
event: eventName,
data: dataLines.join("\n"),
};
}
Helpful Tips for Production SSE & Streaming Pipelines
- Never slice raw
Uint8ArrayorBufferby character count: Byte length and character/code-point count differ dramatically in UTF-8; always frame SSE events on byte/decoded delimiters (\n\n) rather than slicing fixed byte lengths. - Watch out for JSON
JSON.parsefailures on split SSEdata:lines: Even with intact UTF-8 characters, a single JSON payload can occasionally be split across multipledata:lines in an SSE event—joindataLineswith\nbefore callingJSON.parse. - Ensure
Content-Type: text/event-stream; charset=utf-8on upstream emitters: Explicitly declaring UTF-8 on both server and client avoids ambiguous charset fallbacks and keeps non-Latin scripts and emojis intact end-to-end.
You must log in or register to comment.
