Why does an AI chatbot's answer appear word by word instead of as one whole paragraph? Because the answer is sent with streaming: the model's answer is sent piece by piece while it is being made, not all at once when it's finished. It's like a restaurant that brings each dish out as soon as it's cooked. You can start eating while the kitchen is still cooking the rest. When you're full, you can say "stop", and the kitchen stops. Without streaming, every dish waits in the kitchen until the last one is done. The total cooking time is the same, but it feels far longer. In this picture, the kitchen is the model, each dish is a piece of the answer, and "stop" is the Stop button in the chat window.
Why streaming
A model produces its answer token by token. Without streaming, a Bookshop customer stares at a spinner (a turning loading icon) until the last token is done. With streaming, the first word appears almost right away, and the rest follows. The model doesn't finish any sooner. What changes is that users don't have to wait for all of it before they start reading. As a bonus, users can stop an answer that's going the wrong way halfway through.
SSE from OpenAI: event by event
Send stream: true in the body of the request to POST /v1/responses. The answer comes back as SSE (Server-Sent Events): the HTTP standard for a one-way flow of data, from server to client. The response has the header Content-Type: text/event-stream. The flow is made of events, which are small messages. Each event is an event: line (the event's name) and a data: line (its content, in JSON), then one blank line. These are two events that carry pieces of text:
event: response.output_text.delta
data: {"type":"response.output_text.delta","item_id":"msg_demo1","output_index":0,"content_index":0,"delta":"“","sequence_number":4,"logprobs":[]}
event: response.output_text.delta
data: {"type":"response.output_text.delta","item_id":"msg_demo1","output_index":0,"content_index":0,"delta":"The","sequence_number":5,"logprobs":[]}
The order of Responses API events (OpenAI's API reference, checked October 2026):
response.created,response.in_progress,response.output_item.added,response.content_part.added.response.output_text.delta, many times. The piece of text is in thedeltafield.response.output_text.done,response.content_part.done,response.output_item.done.- Finally,
response.completed, which carriesusage.
On failure an error or response.failed event arrives. There is no data: [DONE] line like in Chat Completions.
Other providers use other event names: Anthropic uses message_start, content_block_delta (the text is in delta.text) and message_stop. Ollama doesn't use SSE at all: it sends one JSON object per line.
Take a stand-in answer (a fixed answer, not from a model): "“The Rainbow Troops” is still in stock, 12 left. Want to check “Beauty Is a Wound” too? 5 left." Sent in exactly this format, it is 36 events, 28 of them deltas, 7,648 bytes in all.
Reading the stream correctly
res.body (the body of a fetch response) is a ReadableStream: a flow of bytes that you read piece by piece through a reader from getReader(). Each reader.read() gives one piece (a Uint8Array, a run of bytes). The network decides the size of that piece, not the edges of events or letters. The code below sits inside the reader.read() loop: value is the piece of bytes, decoder is a TextDecoder (it turns bytes into text), and onEvent is a function that receives each event. This naive version (simple, but wrong) hits two problems:
// WRONG
const text = decoder.decode(value); // each piece decoded on its own
for (const line of text.split("\n")) {
if (line.startsWith("data: ")) onEvent(JSON.parse(line.slice(6))); // a line can be cut
}
Guess first: the server sends the text “Beauty Is a Wound”, and you turn each piece of bytes into text on its own with decoder.decode(value), as above. What can appear on screen?
- Split letters.
“(the opening quote mark) is 3 bytes (E2 80 9C). With 89-byte pieces, piece 47 ends right afterE2 80. When each piece is decoded (turned into text) on its own, the incomplete bytes become the replacement character�. The screen shows��Beauty Is a Wound”. - Split lines. One delta
data:line is about 150 bytes long. When a piece ends in the middle of it,JSON.parsethrows aSyntaxErrorand that delta is lost.
The correct version uses one TextDecoder for the whole stream, with { stream: true }: the bytes of an incomplete letter are kept until the next piece arrives. It also uses a buffer (a place that holds text for a while). New text is added to the buffer, and an event is handled only after the blank line that ends it ("\n\n") has arrived:
async function readSSE(body, onEvent) {
const reader = body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true }); // incomplete bytes are kept for later
let edge;
while ((edge = buffer.indexOf("\n\n")) !== -1) {
const block = buffer.slice(0, edge); // one whole event
buffer = buffer.slice(edge + 2); // the rest waits for the next piece
const data = block.split("\n").filter((b) => b.startsWith("data: ")).map((b) => b.slice(6)).join("\n");
if (data) onEvent(JSON.parse(data));
}
}
}
What each reader shows, from that English stream, computed with the Lab's reader code:
| Piece size | Reader | What appears |
|---|---|---|
| 89 bytes | naive | nothing: 34 SyntaxErrors, every delta lost |
| 89 bytes | buffered, without { stream: true } |
... Want to check ��Beauty Is a Wound” too? 5 left. |
| 1,024 bytes | naive | The Rainbow Troops” still in stock, left. Want to checkBeauty Is a Wound too? 5 left. (5 deltas lost) |
| any | readSSE above |
“The Rainbow Troops” is still in stock, 12 left. Want to check “Beauty Is a Wound” too? 5 left. |
The 1,024-byte row is the most dangerous: the sentence looks almost right, so the bug isn't noticed in testing.
Other options: you don't have to write readSSE yourself (checked November 2026).
| Way | When to pick it |
|---|---|
Hand-written readSSE (this lesson) |
The default here: you see what is in the stream, it needs only fetch and no extra package, and the browser uses it too. |
Official SDK: for await (const event of await client.responses.create({ ...options, stream: true })) in the openai package, or client.messages.stream({ ... }).on("text", ...) in @anthropic-ai/sdk |
A server with one provider: the SDK reads the SSE and gives you each event as an object. |
streamText from the AI SDK (the LangChain / Vercel AI SDK lesson) |
You want to switch providers without a rewrite, or you use useChat in React. |
Forwarding to the browser
The Bookshop server reads OpenAI's stream with readSSE, then forwards the pieces of text to the browser as its own SSE:
app.post("/api/assistant/stream", async (req, res) => {
const controller = new AbortController();
res.on("close", () => {
if (!res.writableFinished) controller.abort(); // the browser left: stop the request to OpenAI too
});
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
try {
const upstream = await fetch("https://api.openai.com/v1/responses", {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.OPENAI_API_KEY}` },
body: JSON.stringify({ model: "gpt-6-luna", reasoning: { effort: "none" }, input: req.body.question, stream: true }),
signal: controller.signal,
});
await readSSE(upstream.body, (event) => {
if (event.type === "response.output_text.delta") res.write(`data: ${JSON.stringify({ text: event.delta })}\n\n`);
});
} catch (err) {
if (err.name !== "AbortError") console.error(err); // AbortError: the browser has gone
}
res.end();
});
AbortController is JavaScript's built-in tool for cancelling a fetch. In this route, if the browser closes the connection before the answer is finished, controller.abort() cancels the request to OpenAI too.
The code above doesn't check upstream.ok yet (upstream is the response from OpenAI). If the API key is wrong (401) or the quota is used up (429), OpenAI answers with JSON, not SSE. So readSSE finds no event, and the browser gets an empty 200. An error or response.failed event in the middle of the stream is also lost, because the code above forwards only deltas. Add this check between fetch and readSSE, and forward the error events too:
if (!upstream.ok) {
console.error("OpenAI refused:", upstream.status, await upstream.text()); // details for the server log
res.status(502).write(`data: ${JSON.stringify({ error: "The assistant can't answer right now." })}\n\n`);
return res.end();
}
await readSSE(upstream.body, (event) => {
if (event.type === "response.output_text.delta") res.write(`data: ${JSON.stringify({ text: event.delta })}\n\n`);
if (event.type === "error" || event.type === "response.failed") res.write(`data: ${JSON.stringify({ error: "The answer was cut off." })}\n\n`);
});
In the browser, check res.ok, and show event.error apart from the answer.
In the browser, use fetch again, not EventSource (the browser's built-in tool for receiving SSE), because EventSource can only GET without a body. Add an AbortController for the Stop button. In this code, stopButton is the Stop button on the page, and answerEl is the element the answer is written into:
const controller = new AbortController();
stopButton.onclick = () => controller.abort();
const res = await fetch("/api/assistant/stream", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ question: "Is The Rainbow Troops still in stock?" }),
signal: controller.signal,
});
try {
await readSSE(res.body, (event) => {
answerEl.textContent += event.text; // textContent, not innerHTML
});
} catch (err) {
if (err.name !== "AbortError") throw err; // Stop was pressed: not an error
}
When Stop is pressed, this happens in order:
reader.read()rejects with anAbortError.- The connection to the server closes.
- On the server,
res.on("close")runs. - The request to OpenAI is cancelled as well.
⚠️ Broken letters, lost words and a stream the proxy holds back
decode(value)without{ stream: true }. Multi-byte letters (letters written with more than 1 byte, such as“ ” éand emoji) split at a piece boundary become�.JSON.parseper line without a buffer. Deltas whose line got cut vanish without any message. With large pieces, the sentence is only missing a few words.innerHTML += text. A model's answer is outside text: it can break the HTML or carry a script. UsetextContent, or render it as text in React.- A proxy that holds the stream back. A proxy is a server in between, in front of your app. Nginx (used by Laravel Forge, for example) can buffer the pieces until the response ends, so users still wait for all of it. Send the header
X-Accel-Buffering: noon your stream response.
TL;DR: Streaming sends the model's answer piece by piece while it is being made. Users start reading without waiting for all of it, and can stop it. OpenAI uses SSE (Server-Sent Events, a one-way flow of events from the server, text/event-stream): each event is event: + data: + a blank line. The events go from response.created, through response.output_text.delta many times (text in delta), to response.completed (carrying usage). There is no closing [DONE] line. Read res.body (the body of the fetch response) with getReader(), one TextDecoder (it turns bytes into text) with { stream: true }, and a buffer (a holding place for text) that handles each event once its blank line ("\n\n") arrives. Without { stream: true }, you get �. Without the buffer, deltas are lost. The server forwards the deltas to the browser as its own SSE, and cancels the request to OpenAI when the browser leaves. The browser uses fetch + AbortController (it cancels a fetch) for the Stop button, and writes the answer with textContent.
⚡ An answer that flows
Guess first: with streaming, the model's answer is sent piece by piece while it is being made. Does the model finish writing its answer sooner?
No. The model doesn't finish any sooner. What changes is that the first word appears almost right away, so users start reading without waiting for all of it.
Meaning: Users read while the model is still writing. As a bonus, users can stop an answer that's going the wrong way halfway through.
⚡ SSE: event by event
Write:
event: response.output_text.delta
data: {"type":"response.output_text.delta","item_id":"msg_demo1","output_index":0,"content_index":0,"delta":"The","sequence_number":5,"logprobs":[]}
Meaning: Send stream: true in the request body to the Responses API, and the answer comes back as SSE (Server-Sent Events, text/event-stream): a flow of events (small messages) from the server. Each event is an event: line, a data: line, then one blank line. The piece of text is in the delta field.
⚡ One decoder, one buffer
Write:
buffer += decoder.decode(value, { stream: true }); // incomplete bytes are kept for later
Meaning: value is one piece of bytes from the network, and decoder is one TextDecoder (it turns bytes into text) for the whole stream. A network piece can end in the middle of a letter or a line. Without { stream: true }, a split “ (3 bytes) becomes �. buffer holds the text until the blank line ("\n\n") that ends an event arrives. Without a buffer, a cut data: line makes JSON.parse fail, and its delta is lost.
⚡ Stop and textContent
Meaning: The browser uses fetch (not EventSource, the browser's built-in tool for SSE, which can only GET) plus an AbortController (it cancels a fetch) for the Stop button. A model's answer is outside text, so write it with textContent, not innerHTML.