Claude API Streaming Chunk Handling in JavaScript
The problem with raw streaming chunks
When you stream a response from the Claude API, you don't get one clean JSON object per network packet. You get a raw byte stream that gets split arbitrarily by the network stack, which means a single logical event can arrive split across two chunks, or two events can arrive glued together in one chunk. If you try to JSON.parse() each chunk directly, your code will throw on roughly every third response.
The fix is a small buffering layer that sits between the raw fetch response stream and your event handler. This article shows exactly how to write that layer in JavaScript, what each Claude event type looks like, and the edge cases that trip people up (partial UTF-8 characters, multi-event chunks, tool-use deltas, and stream errors).
What a Claude stream actually sends
Claude streams responses as Server-Sent Events (SSE). Each event looks like this on the wire:
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}
A full response is a sequence of these events in a fixed order:
message_start— metadata about the message (id, model, role)content_block_start— a new block begins (text or tool_use)content_block_delta— incremental text or partial JSON for tool inputcontent_block_stop— the block is completemessage_delta— usage and stop_reason updatesmessage_stop— the stream is finished
Each data: line is a separate JSON object, but the browser or Node's fetch body reader doesn't know or care about that boundary — it just hands you bytes.
Reading the stream with fetch
In a browser or modern Node.js, response.body is a ReadableStream. You read it with a TextDecoder and manually split on newlines:
async function streamResponse(response, onEvent) {
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(); // last line may be incomplete, keep it for next loop
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
const payload = line.slice(6).trim();
if (payload === '[DONE]') return;
try {
const event = JSON.parse(payload);
onEvent(event);
} catch (err) {
// This should be rare if buffering is correct, but log it
// instead of crashing the whole stream
console.error('Failed to parse SSE chunk', payload, err);
}
}
}
}
Two details matter here:
decoder.decode(value, { stream: true })tells the decoder a multi-byte UTF-8 character might be split across chunks. Withoutstream: true, emoji and non-Latin text will occasionally come out corrupted.buffer = lines.pop()keeps the last, possibly-incomplete line for the next read instead of trying to parse it immediately. This is the single most common bug in hand-rolled SSE parsers — people parse every line they get instead of holding back the tail.
Accumulating text deltas
Once events are parsed, you need to turn a stream of content_block_delta events into usable text:
function createAccumulator() {
let fullText = '';
const toolInputs = {};
return {
handleEvent(event) {
switch (event.type) {
case 'content_block_delta':
if (event.delta.type === 'text_delta') {
fullText += event.delta.text;
} else if (event.delta.type === 'input_json_delta') {
const idx = event.index;
toolInputs[idx] = (toolInputs[idx] || '') + event.delta.partial_json;
}
break;
case 'message_delta':
// event.delta.stop_reason, event.usage available here
break;
case 'error':
throw new Error(event.error.message);
}
},
getText: () => fullText,
getToolInputs: () => toolInputs
};
}
Tool use is the trickiest part: tool input arguments arrive as partial JSON strings, not partial objects. You cannot JSON.parse() them until content_block_stop fires for that block — concatenate the fragments first, parse once at the end.
Handling mid-stream errors
Claude can send an error event mid-stream (for example, if the model hits an internal overload after already sending partial output). Your chunk handler must check for event.type === 'error' on every event, not just at connection level — a 200 OK response with a stream that started fine can still fail partway through. Wrap the event loop in a try/catch and make sure partial text already accumulated is preserved and surfaced to the UI rather than discarded.
Backpressure and UI updates
If you're piping deltas straight into a React state update or a DOM write on every single token, you'll cause excessive re-renders on fast models. Batch updates with requestAnimationFrame or a small setTimeout debounce (16–50ms) instead of calling setState on every content_block_delta. This keeps chunk handling logic separate from render logic, which also makes it easier to unit test the parser independently of your UI framework.
Doing this without hand-rolled buffering
If you're building against SubToAPI instead of the raw Anthropic API, the chunk-level SSE framing is identical — SubToAPI proxies Claude's streaming format so your existing parser works unmodified once you point requests at https://api.subtoapi.app/v1/messages with Authorization: Bearer $SUBTOAPI_KEY. What you get on top is a sub_live_... API key you can issue per app or per customer, usage metadata per request, and a dashboard to see which key is burning through tokens — useful once you have more than one streaming integration in production. See /docs/streaming for the exact event sequence and /docs/quickstart for a minimal working example. Plans start at €9/month with a free trial at /signup, and the full breakdown is at /pricing.
Testing your parser
Don't test only against a live API — network conditions that split chunks unpredictably are hard to reproduce on demand. Instead, write a fixture with a known SSE payload, split it at random byte offsets, and feed it through your reader in pieces to confirm the buffer-and-flush logic reassembles it correctly regardless of where the splits land.
FAQs
Why does JSON.parse() sometimes throw on a Claude streaming chunk? Because a single network read can contain a partial SSE event or multiple events glued together. Buffer on newlines and only parse complete data: lines, keeping incomplete trailing lines for the next read.
How do I parse tool_use arguments while streaming? Tool input arrives as input_json_delta events with partial JSON strings. Concatenate the fragments per content block index and run JSON.parse() only once, after content_block_stop fires for that block.
Do I need a different parser for SubToAPI vs. the raw Anthropic API? No. SubToAPI streams the same SSE event format, so a parser built against the raw API works unchanged — see /docs/messages for the request shape and /docs/streaming for event details.