← Blog

Claude API Streaming SSE Implementation Guide

2026-11-17 · 5 min read · SubToAPI Team

What SSE streaming means for the Claude API

When you call the Claude API with "stream": true, the response isn't a single JSON blob — it's a stream of Server-Sent Events (SSE) delivered over a long-lived HTTP connection. Each event is a small chunk of the model's output, sent as soon as it's generated. This is how you get the token-by-token "typing" effect in chat UIs, and it's also how you keep response latency low for longer completions: the client starts rendering text before the full answer exists.

This guide covers the actual wire format Claude uses, how to parse it correctly (including the easy mistakes), and how to build a production-grade streaming client — whether you're hitting the Claude API directly or a compatible gateway like SubToAPI.

The SSE event format

SSE is just HTTP with a specific text format: each event is a block of lines starting with event: and data:, separated by blank lines. Claude's streaming API sends a sequence of named events, not just raw data: lines, which trips up people copying generic SSE tutorials.

The typical event sequence for a single message looks like this:

event: message_start
data: {"type":"message_start","message":{"id":"msg_01...","role":"assistant",...}}

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":" there"}}

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 event line tells you what kind of payload follows, and the data line carries the JSON. If you're using a tool-calling conversation, you'll also see content_block_start events where content_block.type is tool_use, followed by input_json_delta chunks that stream partial JSON for the tool arguments — not plain text deltas. Parsing those as text will silently corrupt your tool calls, so always branch on content_block.type before deciding how to handle deltas.

Implementing an SSE parser from scratch

Most HTTP libraries don't parse SSE for you — you get raw bytes. Here's a minimal, dependency-free parser using fetch and a ReadableStream reader in JavaScript:

async function streamMessage(url, headers, body) {
  const response = await fetch(url, {
    method: "POST",
    headers,
    body: JSON.stringify({ ...body, stream: true }),
  });

  const reader = response.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 lines = buffer.split("\n");
    buffer = lines.pop(); // keep incomplete line for next chunk

    let eventType = null;
    for (const line of lines) {
      if (line.startsWith("event:")) {
        eventType = line.slice(6).trim();
      } else if (line.startsWith("data:")) {
        const data = JSON.parse(line.slice(5).trim());
        handleEvent(eventType, data);
      }
    }
  }
}

function handleEvent(eventType, data) {
  if (eventType === "content_block_delta" && data.delta.type === "text_delta") {
    process.stdout.write(data.delta.text);
  }
  if (eventType === "message_stop") {
    console.log("\n--- done ---");
  }
}

Three details matter here:

Reconstructing the full message

For most apps you need both the live stream and the final assembled message (for logging, token counts, or storage). Accumulate deltas as they arrive:

let fullText = "";
let usage = null;

function handleEvent(eventType, data) {
  if (eventType === "content_block_delta" && data.delta.type === "text_delta") {
    fullText += data.delta.text;
  }
  if (eventType === "message_delta" && data.usage) {
    usage = data.usage;
  }
}

By the time message_stop fires, fullText holds the complete response and usage holds token counts for billing or logging.

Error handling and reconnection

Streaming connections can drop mid-response — proxies time out, mobile networks hiccup, load balancers reset idle connections. A few defensive patterns:

Streaming through SubToAPI

If you're already using SubToAPI to turn your Claude access into a managed HTTPS API, streaming works the same way — it's the same SSE event format, just authenticated with your sub_live_... application key instead of a raw Anthropic key:

curl -N https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4",
    "max_tokens": 1024,
    "stream": true,
    "messages": [{"role": "user", "content": "Explain SSE in two sentences."}]
  }'

The -N flag disables curl's output buffering so you see events as they arrive instead of all at once at the end — useful for debugging your parser before wiring it into an app. SubToAPI also attaches usage metadata to the message_delta event so you can track per-key or per-seat consumption without a second API call. See the streaming docs and the general Messages reference for the full event schema, or start with the quickstart if you're setting up your first key. Plans start with a free trial at signup; pricing details are on the pricing page.

Questions

Does Claude's streaming API use plain SSE or a custom protocol? It's standard Server-Sent Events over HTTP, with named event: lines (message_start, content_block_delta, message_stop, etc.) and JSON data: payloads — any standard SSE-capable HTTP client can consume it.

Why does my parser break on tool-use streaming but work for text? Tool calls stream as input_json_delta events with partial JSON fragments, not text_delta events. You need to branch on content_block.type and delta.type and accumulate tool-call JSON separately from text content.

How do I get token usage from a streamed response? Usage data arrives in the message_delta event near the end of the stream (and sometimes split between message_start for input tokens and message_delta for output tokens) — accumulate it as events arrive rather than expecting one final summary object.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →