Loading...
for await (const chunk of res.body.pipeThrough(new TextDecoderStream())) {
const event = JSON.parse(chunk.replace('data: ', ''));
render(event.text);
}let buffer = '';
for await (const chunk of res.body.pipeThrough(new TextDecoderStream())) {
buffer += chunk;
const events = buffer.split('\n\n');
buffer = events.pop();
for (const e of events) render(JSON.parse(e.replace(/^data: /, '')).text);
}Buffering until a blank line handles events split across chunks, which a direct JSON.parse of each chunk breaks on.
AbortController.SSE is enough for one-way token streaming from server to browser over plain HTTP. WebSocket is needed when both sides send messages continuously.
Something between the server and browser buffers it, often a proxy or compression. Disable buffering for the route and flush each chunk.
Only for GET requests without custom headers. For POST with a body, read the stream with fetch and parse the events yourself.