Why Simple Splitting Breaks SSE Streams
When streaming chat completions from OpenAI in Node.js, data arrives in raw network chunks rather than complete messages. A single chunk might contain half a JSON object, multiple events at once, or a split multi-byte character (like an emoji). Also, OpenAI sends data: [DONE] at the end instead of JSON.
If you call JSON.parse() directly on each raw chunk, your code will crash with syntax errors.
How to Parse SSE Chunks Cleanly
To handle this safely:
- Decode with
{ stream: true }: UseTextDecoderso multi-byte characters split across chunks are decoded properly without breaking. - Keep a string buffer: Append decoded text to a
bufferstring. - Split on
\n\n: In the SSE format, separate events with two newlines. Keep the last piece inbufferbecause it may still be incomplete. - Extract
data:lines: Read lines starting withdata:, stop if the payload is[DONE], and parse the JSON to readdelta.content.
Node.js Example
async function streamOpenAIChat(apiKey, payload) {
const response = await fetch("[https://api.openai.com/v1/chat/completions](https://api.openai.com/v1/chat/completions)", {
method: "POST",
headers: {
"Authorization": `Bearer \${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ ...payload, stream: true }),
});
if (!response.ok || !response.body) {
const errorText = await response.text().catch(() => "");
throw new Error(`Request failed (${response.status}):${errorText}`);
}
const decoder = new TextDecoder();
let buffer = "";
for await (const chunk of response.body) {
buffer += decoder.decode(chunk, { stream: true });
const parts = buffer.split("\n\n");
// Save the last part in case the event is not finished yet
buffer = parts.pop() ?? "";
for (const part of parts) {
const lines = part
.split("\n")
.filter((line) => line.startsWith("data:"))
.map((line) => line.slice(5).trim());
if (lines.length === 0) continue;
const rawData = lines.join("\n");
if (rawData === "[DONE]") {
return;
}
const parsed = JSON.parse(rawData);
const token = parsed.choices?.[0]?.delta?.content;
if (token) {
process.stdout.write(token);
}
}
}
// Flush any leftover bytes from the decoder
decoder.decode();
}
Quick Tips for Real Apps
- Ignore comment lines: SSE comments start with
:. Filtering fordata:naturally skips them. - Add an
AbortController: Pass asignaltofetchso users can stop generation or time out slow streams. - Use libraries for bigger apps: Packages like
eventsource-parseror the officialopenaiSDK handle edge cases automatically if your streaming logic grows complex.
You must log in or register to comment.