Replacement characters «�» instead of text in SSE
A multi-byte character was cut at a chunk boundary. One decoder and one flag fix it, and the same mistake is hiding one level up, in the SSE parsing.
What it means
Some characters in an SSE stream come out as � (U+FFFD, the replacement
character). Short responses have none, long ones one or two per paragraph.
The server's encoding is fine; the chunk boundary is not.
How to fix it
In UTF-8 a non-ASCII character takes 2 to 4 bytes
(RFC 3629 § 3),
and a chunk can end in the middle of one. If «я» is cut in half, one chunk ends
with 0xD1 and the next starts with 0x8F. Decoded separately, they give two �. A
split 4-byte emoji gives two to four. ASCII text never shows this.
The fix is one decoder for the whole stream plus stream: true.
const decoder = new TextDecoder(); // ONE for the whole stream
const reader = response.body.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) break;
handle(decoder.decode(value, { stream: true })); // ← the flag
}
const tail = decoder.decode(); // "" normally
if (tail) console.warn('stream ended mid-character');
stream: true holds unfinished bytes until the next call. The state lives in
the instance, so a new TextDecoder() per chunk does not help. The final
decode() returns "" for a clean stream and "�" for one cut
mid-character.
TextDecoderStream does the same.
const reader = response.body
.pipeThrough(new TextDecoderStream())
.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) break;
handle(value);
}
for await (const chunk of stream) needs async iteration over
ReadableStream, which Chrome 124 and Firefox 110 support and Safari does not yet. TextDecoderStream
works from Safari 14.1, so the reader loop is more portable.
Node has a global TextDecoder, so the same code runs. The Node form of the
bug is chunk.toString() per chunk; StringDecoder from
node:string_decoder keeps state like stream: true.
EventSource decodes the stream itself. The bug hits code that reads SSE or
NDJSON through fetch, needed for custom headers or a POST body.
The other half of the same bug
Chunk boundaries do not match event boundaries either, so data: {"a":1}\n\n
can arrive in two pieces. Keep a buffer that outlives the chunk.
let buffer = '';
function handle(text) {
buffer += text;
if (buffer.endsWith('\r')) return; // \r or \r\n? wait for the next chunk
buffer = buffer.replace(/\r\n|\r/g, '\n'); // SSE allows \n, \r\n and bare \r
const parts = buffer.split('\n\n');
buffer = parts.pop() ?? ''; // the tail waits for next time
for (const part of parts) emit(part);
}
The last element of parts is "" or an unfinished event; pop() returns it
to the buffer. At done, emit what is left.
Normalise line endings on the buffer, not the chunk. \r and \n can land in different
chunks, and a per-chunk replace leaves a stray \r.
By default (ignoreBOM: false), TextDecoder and TextDecoderStream strip a
leading BOM (RFC 3629 § 6). Node's toString('utf8') and StringDecoder keep it.
A surviving U+FEFF joins the first field name, and the parser drops that line.
See it on your own traffic
Solpuga decodes the stream apart from your code, a whole line at a time, so a
character split between chunks comes out intact. If events are clean in Solpuga but
� shows on your page, the bug is in your decoder. If � shows in Solpuga too, the server
sent invalid UTF-8. NDJSON and other non-SSE responses are shown as text in
the declared charset (UTF-8 if none), with a note when some bytes are invalid
in it. See Capture & Inspect Traffic.
Tool for this page
SSE stream parserPaste a raw Server-Sent Events stream and see the events, ids, retry hints and framing mistakes.Related
- SSE arrives in one chunk: nginx bufferingServer-Sent Events land all at once instead of streaming. Three layers act on them: proxy_buffering, gzip and the app itself. How to test each.
- The stream dies after 60 seconds: proxy_read_timeoutA stream that dies on the same second is a timeout. Default values in nginx, ALB, Cloudflare, Heroku and Envoy, and why a heartbeat is safer.