← Blog

Claude API Streaming Responses: Implementation Guide

2026-11-12 · 4 min read · SubToAPI Team

Streaming lets your application display Claude's response token by token instead of waiting for the full completion. If you're implementing this for the first time, the core pattern is: set stream: true in your request, read the response body as a stream of server-sent events (SSE), parse each event type, and append text deltas to your UI as they arrive.

This guide walks through a working implementation end to end: the request format, the event types you'll receive, how to parse them correctly, and common mistakes that break streaming in production (buffering, premature connection close, missing error handling). Examples use raw curl and JavaScript so you can adapt them to any backend language.

Why stream at all

Without streaming, a user asking Claude to write a 2,000-word document waits in silence until the entire response is generated, which can take 10-30 seconds. Streaming starts rendering text within a second or two, which is the difference between an app that feels responsive and one that feels broken. It also lets you implement "stop generating" buttons, since you can close the connection mid-stream instead of discarding a completed response.

Enabling streaming in the request

Add "stream": true to your request body. The response content type changes from application/json to text/event-stream, and the connection stays open until the model finishes or you close it.

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" \
  -d '{
    "model": "claude-sonnet-4-5",
    "max_tokens": 1024,
    "stream": true,
    "messages": [{"role": "user", "content": "Explain TCP handshakes"}]
  }'

The event types you need to handle

Claude's streaming format sends a sequence of named SSE events, not just raw text chunks. A typical stream 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":"TCP"}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" uses"}}

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

event: message_stop
data: {"type":"message_stop"}

The only event you need for basic text rendering is content_block_delta with delta.type === "text_delta". The others matter if you're handling tool use blocks, tracking token usage, or detecting why generation stopped.

If the model is calling a tool, you'll also see content_block_start with content_block.type: "tool_use", followed by input_json_delta events that stream the tool's arguments as partial JSON. You need to accumulate these fragments and parse the full JSON only once the block closes — see /docs/tools for the full event sequence when tool use is involved.

Parsing the stream in JavaScript

Here's a minimal, dependency-free parser using the Fetch API's ReadableStream:

async function streamMessage(body) {
  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({ ...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

    for (const line of lines) {
      if (!line.startsWith("data: ")) continue;
      const payload = JSON.parse(line.slice(6));

      if (payload.type === "content_block_delta" &&
          payload.delta.type === "text_delta") {
        process.stdout.write(payload.delta.text);
      }
    }
  }
}

The critical detail most implementations get wrong: SSE chunks don't align with JSON object boundaries. A single read() call might return half a line, or several events at once. Always buffer partial lines and split on newlines rather than assuming each chunk is one complete event.

Streaming through a proxy or backend

If your frontend can't call the Claude API directly — because you don't want to expose your API key in client-side code — you'll proxy the stream through your own backend. The backend reads the upstream SSE stream and re-emits it to the client, usually unchanged. The main pitfall here is accidental buffering: some Node.js frameworks and reverse proxies (notably certain Nginx configurations) buffer the full response before forwarding it, which defeats the purpose of streaming. Disable response buffering explicitly and flush each chunk as it arrives.

This is one of the reasons teams move to a managed layer instead of maintaining their own proxy. SubToAPI turns your existing Claude access into an HTTPS API with streaming support built in — you call it the same way, with stream: true, and get the same event format, but authentication uses your own sub_live_... application keys instead of exposing your Anthropic credentials in multiple services. See /docs/streaming for the exact request shape and /docs/quickstart to get a key running in a few minutes.

Handling errors mid-stream

A stream can fail after it has already started sending content — for example, if the model hits a content filter or the connection drops. Watch for an error event type and for abrupt stream termination without a message_stop event. Always wrap the read loop in a try/catch and have a fallback (retry with backoff, or surface a partial-response notice to the user) rather than silently truncating output.

try {
  await streamMessage(requestBody);
} catch (err) {
  console.error("Stream interrupted:", err.message);
  // retry logic or user-facing fallback here
}

Questions

Does streaming cost more than non-streaming requests? No. Token-based pricing is identical whether you stream or not; you're billed for the same input and output tokens either way.

Can I stream tool use calls, not just text? Yes. Tool use blocks stream as input_json_delta events containing partial JSON fragments that you accumulate and parse once the block closes — see /docs/tools for the full sequence.

Why does my stream appear all at once instead of incrementally? Usually a buffering layer between your server and the client — a reverse proxy, a framework middleware, or even console.log batching. Check that each hop forwards chunks immediately rather than waiting for the full response.

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 →