Server-Sent Events Claude API Example (curl + JS)
If you're searching for a server sent events Claude API example, you're probably trying to stream a response token-by-token instead of waiting for the full completion. Claude's API (and SubToAPI's compatible endpoint) supports this via the stream parameter, which switches the response format from a single JSON blob to a sequence of text/event-stream events that you parse as they arrive.
This article shows exactly what those events look like, how to parse them in curl and JavaScript, and the common mistakes that break SSE parsing in production.
What Server-Sent Events Actually Look Like
SSE is a plain-text protocol over HTTP. The server keeps the connection open and sends discrete chunks, each prefixed with event: and data: lines, separated by a blank line. A Claude-style streaming response looks like this:
event: message_start
data: {"type":"message_start","message":{"id":"msg_01abc","role":"assistant"}}
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"}}
event: message_stop
data: {"type":"message_stop"}
Each data: line contains a JSON object. Your job as the client is to read these line by line, buffer until you hit a blank line (end of event), parse the JSON, and react to the type field.
Minimal curl Example
curl can display raw SSE output directly, which is useful for debugging before you write client code:
curl -N https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 512,
"stream": true,
"messages": [
{"role": "user", "content": "Write a haiku about rain"}
]
}'
The -N flag disables curl's output buffering so you see events as they arrive instead of all at once at the end. If you omit -N, curl will still work correctly — it just won't look like streaming in your terminal.
JavaScript Example: Parsing SSE from fetch
Browsers have a native EventSource API, but it only supports GET requests without custom headers, which doesn't work for authenticated POST requests to the Claude API. Instead, you read the response body as a stream and parse SSE manually:
async function streamMessage(prompt) {
const response = 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-3-5-sonnet-20241022",
max_tokens: 512,
stream: true,
messages: [{ role: "user", content: prompt }]
})
});
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 events = buffer.split("\n\n");
buffer = events.pop(); // keep incomplete event for next chunk
for (const chunk of events) {
const dataLine = chunk.split("\n").find(l => l.startsWith("data:"));
if (!dataLine) continue;
const payload = JSON.parse(dataLine.slice(5).trim());
if (payload.type === "content_block_delta") {
process.stdout.write(payload.delta.text);
}
if (payload.type === "message_stop") {
console.log("\n[stream complete]");
}
}
}
}
streamMessage("Write a haiku about rain");
The key detail here is the buffer-and-split logic. Network chunks don't align with SSE event boundaries — a single read() call might give you half an event, a full event, or three events at once. Always split on the double-newline (\n\n) and hold back the last incomplete segment for the next read.
Handling Event Types Correctly
A real streaming response contains several event types in order, and you need to handle each one, not just content_block_delta:
message_start— fires once, contains the message ID and rolecontent_block_start— marks the beginning of a content block (text or tool use)content_block_delta— the actual incremental text or tool input, fired many timescontent_block_stop— a content block finishedmessage_delta— carries usage and stop_reason updatesmessage_stop— the stream is done
If your code only listens for content_block_delta and ignores the rest, it'll work for simple text generation but break the moment you add tool use, since tool calls stream as structured JSON deltas inside separate content blocks. Full event documentation, including tool use streaming, is at /docs/streaming and /docs/tools.
Common Mistakes
Treating each read() as one event. This is the most frequent bug. Fix it with the buffer-and-split pattern above.
Forgetting to set stream: true. Without it, you get a normal JSON response and no SSE at all — an easy thing to overlook when copy-pasting from a non-streaming example.
Not handling connection drops. Long streams over flaky networks will occasionally disconnect mid-response. Production code should catch the error, check if message_stop was received, and retry the request with the partial output discarded if not.
Parsing data: lines with naive string splitting on commas or spaces. Always JSON.parse the payload — don't try to regex individual fields out of it.
Why This Matters for Production Apps
Streaming isn't just a UX nicety — it's often required for acceptable latency on longer completions, since users see the first tokens in under a second instead of waiting for the entire response to generate. If you're building this directly against Anthropic's API, you own the SSE parsing, reconnect logic, and usage tracking yourself. SubToAPI exposes the same streaming interface over a stable HTTPS endpoint with application-level API keys, so you can issue separate sub_live_... keys per app or environment while keeping one underlying Claude subscription. See /docs/quickstart for a full working example and /docs/messages for the non-streaming equivalent.
questions
Does Claude's API support native SSE or do I need a library? It's native text/event-stream over standard HTTP — no special library is required, just a client that can read a streamed response body and split it on event boundaries.
Can I use the browser's built-in EventSource for this? Not directly, because EventSource only supports GET requests and can't send custom Authorization headers. Use fetch with a readable stream reader instead, as shown above.
What happens if my connection drops mid-stream? You'll stop receiving events without necessarily getting an error. Track whether message_stop arrived; if not, treat the response as incomplete and retry the request.