← Blog

Claude API Server-Sent Events Setup Guide

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

What SSE setup means for the Claude API

If you're searching for "claude api server sent events setup," you're probably trying to stream a response token-by-token instead of waiting for the full completion to arrive — the kind of experience you see in Claude's own chat UI. The short answer: you set "stream": true in your request body, read the HTTP response as a stream rather than a single JSON payload, and parse each data: line as it arrives.

This article walks through the actual mechanics — request headers, event types, parsing logic, error handling, and a working client in both curl and JavaScript — so you can get SSE working against the Claude API (or a compatible proxy) without guessing at the wire format.

How server-sent events work with Claude

Server-sent events (SSE) are a simple, one-way streaming protocol built on top of plain HTTP. The server keeps the connection open and sends a sequence of text events, each prefixed with data: and separated by blank lines. No WebSocket handshake, no special client library required — any HTTP client that can read a response body incrementally can consume it.

For Claude, streaming is enabled with one field:

{
  "model": "claude-sonnet-4-5",
  "max_tokens": 1024,
  "stream": true,
  "messages": [
    { "role": "user", "content": "Explain SSE in two sentences." }
  ]
}

With stream: true, the response Content-Type becomes text/event-stream instead of application/json, and the body arrives as a series of named events rather than one JSON object.

The event sequence you'll see

A typical streamed Claude response emits events in this order:

Each event looks like this on the wire:

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

Note the required blank line after each data: line — that's how SSE marks the end of an event. If your parser doesn't split on double newlines, you'll end up concatenating malformed JSON.

Setting up the request correctly

Headers

Your request needs the usual auth header plus a few things SSE clients often get wrong:

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": 512,
    "stream": true,
    "messages": [{"role": "user", "content": "Write a haiku about streams."}]
  }'

The -N flag on curl disables output buffering — without it curl will wait and dump everything at once, which defeats the point of testing SSE from the command line.

Common client-side mistakes

  1. Buffering the whole response. If you're using fetch with .json() or .text(), you're waiting for the stream to close before touching any data. Use response.body.getReader() or a streaming HTTP client instead.
  2. Not handling partial chunks. TCP doesn't guarantee that one data: line arrives in one read — you need to buffer incoming bytes and split on \n\n before parsing.
  3. Ignoring message_delta's stop_reason. If you only read content_block_delta events, you'll miss truncation or tool-use completion signals.
  4. Not handling ping events. Long streams emit periodic ping events to keep the connection alive — your parser should skip these, not error on them.

A minimal JavaScript SSE client

async function streamMessage(payload) {
  const res = 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({ ...payload, stream: true })
  });

  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 parts = buffer.split("\n\n");
    buffer = parts.pop(); // keep incomplete chunk for next read

    for (const part of parts) {
      const line = part.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);
      }
    }
  }
}

This pattern — buffer, split on double newlines, parse the trailing data: line — is the core of every SSE client, regardless of language.

Simplifying SSE with a hosted proxy

If you're building this for a product (not a one-off script), you'll eventually need to handle reconnects, rate-limit backoff, token metadata, and multiple team members hitting the same Claude account without sharing raw credentials. That's the exact problem SubToAPI solves: it sits in front of your Claude access and exposes a standard HTTPS API with sub_live_... application keys, so your SSE client code stays the same while you get per-key usage tracking and seat management for free.

Setup is the same request shape shown above — point your client at https://api.subtoapi.app/v1/messages with Authorization: Bearer $SUBTOAPI_KEY and "stream": true. See the streaming docs for the full event reference, or the quickstart if you're starting from zero. Plans start at €9/month on the pricing page, with a free trial at signup.

questions

Does Claude's SSE stream require a special client library? No. SSE is plain HTTP with a text/event-stream content type. Any HTTP client capable of reading a response body incrementally — fetch with a stream reader, curl -N, Python's requests with stream=True — can consume it without extra dependencies.

Why am I getting one giant blob instead of incremental chunks? Usually it's response buffering on the client, a proxy (like certain CDNs or Nginx configs) that buffers before forwarding, or forgetting "stream": true in the request body. Test with curl -N first to rule out client-side buffering.

What's the difference between content_block_delta and message_delta events? content_block_delta carries the actual incremental text or tool-call JSON fragments as they're generated. message_delta arrives once near the end with final metadata like stop_reason and token usage — don't skip it if you need to know why generation stopped.

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 →