Claude API Streaming Tokens with Server-Sent Events
What "streaming tokens" means in the Claude API
When you call the Claude API with "stream": true, the response isn't one JSON blob delivered after the model finishes thinking — it's a continuous flow of small events sent over a single HTTP connection as the model generates each token. This flow uses server-sent events (SSE), a plain-text protocol built on top of HTTP that lets a server push incremental updates to a client without the client having to poll.
Practically, this means your UI can display Claude's answer word-by-word as it's generated, instead of showing a loading spinner for 5–15 seconds and then dumping the full response at once. This is the same pattern used by ChatGPT-style interfaces, and it's what the Claude API (and compatible proxies like SubToAPI) expose natively when you set the stream parameter.
How SSE works under the hood
Server-sent events are just HTTP responses with a specific content type and a specific text format. The server sets:
Content-Type: text/event-stream
and then writes a series of events, each one looking like this:
event: content_block_delta
data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"Hello"}}
event: content_block_delta
data: {"type":"content_block_delta","delta":{"type":"text_delta","text":" world"}}
Each event is terminated by a blank line. The client reads the stream line by line, buffers until it hits a blank line, and then processes the accumulated data: payload as one event. No polling, no WebSocket handshake — it rides on a normal HTTP connection that both browsers and server runtimes understand natively via EventSource (browser) or a readable stream reader (Node/server).
The Claude streaming event sequence
A typical Claude streaming response emits these event types in order:
message_start— the message object is created, usage counters at zerocontent_block_start— a new content block begins (text or tool_use)content_block_delta— repeated many times, each carrying a small chunk of text or a partial tool-input JSON fragmentcontent_block_stop— the block is completemessage_delta— carries updatedstop_reasonand cumulative output token usagemessage_stop— the stream is finished
If Claude is using tools mid-response, you'll see multiple content_block_start/content_block_delta/content_block_stop cycles — one per content block, whether it's text or a tool_use block with incrementally built JSON arguments.
Reading the stream with curl
For debugging, curl is the fastest way to see raw SSE frames:
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": 256,
"stream": true,
"messages": [{"role": "user", "content": "Count to five."}]
}'
The -N flag disables curl's output buffering so you see events arrive in real time instead of all at once at the end.
Parsing SSE in JavaScript
If you're building a server-side proxy or a Node backend, you don't get EventSource for free — you read the response body as a stream and parse data: lines yourself:
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"content-type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 512,
stream: true,
messages: [{ role: "user", content: "Explain SSE in two sentences." }],
}),
});
const reader = res.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 });
const events = buffer.split("\n\n");
buffer = events.pop(); // keep incomplete chunk for next loop
for (const chunk of events) {
const line = chunk.split("\n").find(l => l.startsWith("data:"));
if (!line) continue;
const json = JSON.parse(line.replace("data:", "").trim());
if (json.type === "content_block_delta" && json.delta?.text) {
process.stdout.write(json.delta.text);
}
}
}
In the browser, EventSource handles the parsing for you, but it only supports GET requests without custom headers — which is why most frontends call their own backend (or a proxy like SubToAPI) rather than hitting a streaming LLM API directly from client-side JavaScript.
Why stream instead of waiting for the full response
- Perceived latency — users see the first words within a second instead of staring at a blank screen for the full generation time.
- Early cancellation — you can abort a request the moment you see the answer going off-track, saving tokens and cost.
- Progressive rendering — chat UIs, code editors, and voice assistants can start acting on partial output (e.g., rendering markdown as it arrives) instead of blocking on completion.
- Tool-call visibility — with streaming, you can show "Claude is using a tool…" indicators as
content_block_startevents fortool_useblocks arrive, before the full tool input JSON is even assembled.
Streaming through SubToAPI
If you're exposing Claude as an HTTPS API inside your own product, you need the same SSE behavior but authenticated with your own application keys instead of a raw Anthropic key. SubToAPI turns your Claude access into a standard API with sub_live_... keys, and streaming works the same way — set stream: true on a request to /v1/messages and read the SSE frames exactly as described above. This matters for teams who want usage metadata, per-key rate limits, and seat management on top of a feature they already rely on, without re-implementing the SSE parsing logic for every client app. See the streaming docs and the general messages reference for event shapes, or start with the quickstart if you haven't wired up a key yet. Plans start at the pricing page with a free trial at signup.
Questions
Does Claude API streaming use WebSockets? No. It uses server-sent events over a standard HTTP connection — one request, one long-lived response, no separate handshake protocol or bidirectional channel needed.
Can I get token usage counts while streaming? Yes. The message_delta event near the end of the stream includes cumulative output token usage, and message_start includes input token usage, so you don't need a separate non-streaming call to get those numbers.
What happens if the connection drops mid-stream? You lose the remainder of that generation and need to retry the request from scratch — SSE streams aren't resumable mid-generation, so client code should handle reconnection/retry logic rather than assuming the connection will recover automatically.