Claude API Streaming Response Implementation Guide
Streaming lets you display Claude's response token by token instead of waiting for the full completion, which is what makes chat interfaces feel responsive instead of frozen. The implementation is based on Server-Sent Events (SSE): you send a request with "stream": true, keep the HTTP connection open, and parse a sequence of data: events as they arrive, each containing a small JSON delta of the response.
This article walks through a working implementation in both raw HTTP/curl and JavaScript, explains the event types you'll actually receive, and covers the mistakes that break streaming in production — buffering proxies, incomplete JSON parsing, and dropped connections on long responses.
How Claude API streaming actually works
When you set stream: true on a messages request, the API doesn't return one JSON blob. It returns a stream of events over a single HTTP connection, each formatted as an SSE event:
event: message_start
data: {"type":"message_start","message":{...}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}
event: message_stop
data: {"type":"message_stop"}
The event types you'll see, in order, are roughly:
message_start— the message object is created, usage/model metadata includedcontent_block_start— a new content block begins (text or tool_use)content_block_delta— the actual incremental text or tool input, repeated many timescontent_block_stop— the block is finishedmessage_delta— final usage stats and stop reasonmessage_stop— the stream is done
Your client needs to accumulate content_block_delta text chunks into the final string, and handle ping events (keepalives) by ignoring them.
Implementing streaming with curl
Useful for debugging before writing client code:
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-N \
-d '{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"stream": true,
"messages": [{"role": "user", "content": "Explain SSE in two sentences"}]
}'
The -N flag disables curl's output buffering — without it you won't see chunks arrive incrementally even though the server is streaming correctly. This is the single most common reason people think "streaming isn't working" when it actually is.
Implementing streaming in JavaScript
A minimal fetch-based reader that parses SSE manually:
async function streamMessage(apiKey, prompt) {
const response = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"x-api-key": apiKey,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
body: JSON.stringify({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1024,
stream: true,
messages: [{ role: "user", content: prompt }],
}),
});
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 lines = buffer.split("\n");
buffer = lines.pop(); // keep incomplete line for next chunk
for (const line of lines) {
if (!line.startsWith("data: ")) continue;
const payload = line.slice(6);
if (payload === "[DONE]") continue;
const event = JSON.parse(payload);
if (event.type === "content_block_delta" && event.delta?.text) {
fullText += event.delta.text;
process.stdout.write(event.delta.text); // print as it arrives
}
}
}
return fullText;
}
The critical detail here is buffering raw bytes into lines before parsing JSON. Network chunks don't align with SSE event boundaries — a single data: line can arrive split across two reads. If you JSON.parse on partial data you'll get intermittent crashes that are hard to reproduce locally but show up constantly under real network conditions.
Common streaming failures and fixes
Reverse proxies buffer the response. Nginx, some CDNs, and certain serverless runtimes buffer the full response body before forwarding it, which defeats streaming entirely — you get one big chunk at the end. Fix: disable proxy buffering (proxy_buffering off; in nginx) or use a runtime that supports true streaming responses (not all serverless functions do).
Tool use streams differently. When Claude is calling a tool, the content_block_delta events contain partial JSON for the tool input (input_json_delta), not plain text. You need to accumulate those fragments separately and only parse the JSON once content_block_stop fires for that block. See the tool use docs if you're building an app that mixes streamed text with tool calls.
Long-running connections time out. Load balancers and some HTTP clients have default idle timeouts shorter than a long Claude response. The ping events in the stream exist specifically to keep the connection alive — make sure your infrastructure doesn't have an idle timeout shorter than ~15-30 seconds, since that's roughly the ping interval.
Error handling mid-stream. A stream can fail partway through (rate limit hit, model error) and you'll get an error event instead of message_stop. Always wrap the parsing loop in a try/catch and check for event.type === "error" so a partial response doesn't get silently treated as complete.
Streaming through SubToAPI
If you're building this once and reusing it across an internal tool, a customer-facing feature, and a CI pipeline, re-implementing SSE parsing in every service gets old fast. SubToAPI exposes Claude access as a straightforward HTTPS API with the same streaming semantics — stream: true on a request to /v1/messages returns the identical SSE event sequence described above, but authenticated with a sub_live_... application key instead of managing provider credentials per-service.
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "content-type: application/json" \
-N \
-d '{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"stream": true,
"messages": [{"role": "user", "content": "Explain SSE in two sentences"}]
}'
The parsing code above works unchanged — just swap the host and auth header. See the streaming docs and quickstart for the full event reference, and pricing if you're evaluating it for a team.
Questions
Does streaming cost more than non-streaming requests? No. Token pricing is identical; streaming only changes delivery format, not the number of tokens billed.
Can I stream and still get accurate token usage? Yes. Usage totals arrive in the message_delta event near the end of the stream, after all content deltas but before message_stop.
What's the fastest way to test if my streaming setup is broken? Run the curl example with -N first. If chunks print immediately with curl but not in your app, the bug is in your client's buffering or proxy layer, not the API call itself.