Claude API Streaming Responses with Server-Sent Events
When you call the Claude API with "stream": true, Anthropic doesn't send back one big JSON blob — it sends back a sequence of Server-Sent Events (SSE), each carrying a small piece of the response as it's generated. This is what lets a chat UI show text appearing word-by-word instead of making the user stare at a spinner for ten seconds.
If you're searching for how this actually works, here's the short answer: Claude's streaming API uses standard SSE over a single HTTP connection. The server sends a series of named events (message_start, content_block_delta, message_stop, etc.), each formatted as event: <type> followed by data: <json>, separated by blank lines. Your client reads the stream line by line, accumulates the delta fields, and renders them incrementally. Below is exactly how to implement this correctly, including the parts most people get wrong.
What SSE Actually Looks Like
A raw streaming response from the Messages API looks something like this:
event: message_start
data: {"type":"message_start","message":{"id":"msg_01...","model":"claude-sonnet-4-5","role":"assistant","content":[]}}
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":", world"}}
event: content_block_stop
data: {"type":"content_block_stop","index":0}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":12}}
event: message_stop
data: {"type":"message_stop"}
Each data: line is a complete JSON object. The important ones to handle:
message_start— fires once, gives you the message id and modelcontent_block_start— a new content block begins (text or tool use)content_block_delta— the actual incremental text (or tool input JSON) you appendcontent_block_stop— that block is finishedmessage_delta— carries finalstop_reasonand token usagemessage_stop— the stream is done
There's also ping events the server sends to keep the connection alive — ignore them, don't treat them as errors.
Streaming with curl
curl handles SSE natively if you just avoid buffering:
curl -N https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"stream": true,
"messages": [{"role": "user", "content": "Write a haiku about rivers"}]
}'
The -N flag disables curl's output buffering, which is essential — without it you'll just get the whole response dumped at the end, defeating the point of streaming.
Parsing SSE in JavaScript
In the browser or Node, you read the response body as a stream and split on double newlines:
const response = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"x-api-key": process.env.ANTHROPIC_API_KEY,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
stream: true,
messages: [{ role: "user", content: "Write a haiku about rivers" }],
}),
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let fullText = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const events = buffer.split("\n\n");
buffer = events.pop(); // keep incomplete chunk for next loop
for (const event of events) {
const dataLine = event.split("\n").find((l) => l.startsWith("data:"));
if (!dataLine) continue;
const json = JSON.parse(dataLine.replace("data: ", ""));
if (json.type === "content_block_delta" && json.delta?.text) {
fullText += json.delta.text;
process.stdout.write(json.delta.text);
}
}
}
The two mistakes people usually make: not buffering partial chunks across read() calls (SSE events can be split mid-line across TCP packets), and forgetting that the stream can end with a trailing incomplete event that needs to stay in the buffer until the next read.
Common Pitfalls
- Timeouts behind proxies. Nginx, Cloudflare, and some corporate load balancers buffer responses by default, which kills the "streaming" effect even if your code is correct. You need
proxy_buffering off(nginx) or equivalent. - Error events mid-stream. If something goes wrong after the stream has started (e.g. an overloaded model), Claude sends an
errorevent type instead of silently closing the connection. Always checkjson.type === "error"in your parsing loop. - Tool use streaming. When Claude is calling a tool, the
content_block_deltaevents carryinput_json_deltainstead oftext_delta— you accumulate those into a partial JSON string and parse it oncecontent_block_stopfires. - Token usage only arrives at the end.
input_tokensandoutput_tokensshow up inmessage_startandmessage_deltarespectively — you can't get final cost until the stream closes.
Simplifying This with SubToAPI
If you don't want to maintain SSE parsing logic across multiple apps, languages, or teams, SubToAPI gives you a standard HTTPS API key (sub_live_...) on top of your existing Claude access, with streaming support that follows the same SSE shape described above — see /docs/streaming for the exact event reference and /docs/messages for the request format. You get the same content_block_delta events, plus usage metadata per request without having to track it yourself across the stream lifecycle.
It also means every team member gets their own scoped key instead of sharing one raw API credential, which matters once more than one person is building against Claude. Check /docs/quickstart to get a streaming request running in under five minutes, or see /pricing for plan details — there's a free trial at /signup if you want to test streaming against your own prompts first.
Questions
Does Claude's streaming API use WebSockets? No. It uses Server-Sent Events over a standard HTTP connection — one request, one long-lived response stream, no separate protocol or handshake required.
Can I cancel a stream partway through? Yes, closing the underlying HTTP connection (aborting the fetch or killing the curl process) stops generation. Claude doesn't bill for tokens that weren't generated after cancellation.
Why does my proxy or CDN break streaming? Most reverse proxies buffer responses by default, which holds back chunks until the full response is ready. Disable buffering (e.g. X-Accel-Buffering: no or proxy_buffering off in nginx) for the streaming endpoint specifically.