Claude API Chat Completion Streaming in Node.js
How to stream Claude API chat completions in Node.js
If you're building a chat interface, a CLI tool, or any app where users expect tokens to appear as they're generated, you need streaming. The Claude API supports streaming chat completions over server-sent events (SSE), and in Node.js you can consume that stream with nothing more than the built-in fetch and a simple loop over the response body.
This guide walks through a working Node.js example for streaming Claude responses, how to parse the SSE events correctly, how to handle errors mid-stream, and a faster path if you'd rather skip the SSE parsing entirely.
Why streaming matters for chat completions
Without streaming, your app waits for Claude to generate the entire response before sending anything back to the user. For long answers, that can mean several seconds of a blank screen. Streaming sends tokens as they're produced, so you can render them incrementally — this is the difference between a chat UI that feels instant and one that feels stuck.
Streaming also lets you cancel generation early (useful for "stop" buttons) and start post-processing partial output before the full response lands.
Setting up the request
Claude's streaming API uses SSE: you send a normal POST request with "stream": true in the body, and instead of a single JSON response, you get a stream of data: lines, each containing a JSON event.
Here's a minimal Node.js example using native fetch (Node 18+):
const response = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": process.env.ANTHROPIC_API_KEY,
"anthropic-version": "2023-06-01",
},
body: JSON.stringify({
model: "claude-opus-4",
max_tokens: 1024,
stream: true,
messages: [{ role: "user", content: "Explain event loops in Node.js" }],
}),
});
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 = line.slice(6);
if (payload === "[DONE]") continue;
const event = JSON.parse(payload);
if (event.type === "content_block_delta") {
process.stdout.write(event.delta.text ?? "");
}
}
}
A few things that trip people up here:
- Chunks don't align with SSE lines. A single
read()call might return half an event or several events at once. You have to buffer and split on newlines yourself — this is the most common source of "JSON.parse failed" bugs in streaming code. - Events have types. You'll see
message_start,content_block_delta,content_block_stop, andmessage_stopevents. Onlycontent_block_deltacarries the actual text tokens you want to render. - Keep-alive matters. If your HTTP client or proxy times out idle connections, long streaming responses can get cut off mid-generation. Make sure any reverse proxy or load balancer in front of your Node process has generous read timeouts.
Handling errors mid-stream
Streaming responses can fail after they've already started — a rate limit hit, a context overflow, or a transient network issue. Wrap the read loop in a try/catch and check for an error event type:
try {
// ...read loop from above
} catch (err) {
console.error("Stream interrupted:", err.message);
} finally {
reader.releaseLock();
}
Also check the initial response status before you start reading — a 4xx or 5xx won't stream a body at all, it'll just return a JSON error object synchronously.
Streaming with the Node SDK
If you're using Anthropic's official SDK instead of raw fetch, the streaming API is more ergonomic:
const stream = await anthropic.messages.stream({
model: "claude-opus-4",
max_tokens: 1024,
messages: [{ role: "user", content: "Write a haiku about async/await" }],
});
stream.on("text", (text) => process.stdout.write(text));
await stream.finalMessage();
This handles the chunk buffering and event parsing for you, which is worth it unless you have a specific reason to manage the raw connection yourself.
A simpler path: streaming through SubToAPI
If you already route Claude access through SubToAPI, streaming works the same way but with one key difference: you're authenticating with a sub_live_... application key instead of managing per-user Claude credentials, and you get per-key usage metadata on every call.
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-opus-4",
max_tokens: 1024,
stream: true,
messages: [{ role: "user", content: "Stream me a short story" }],
}),
});
The SSE parsing loop is identical to the example above — same event types, same content_block_delta chunks. The parts you get for free are request-level usage tracking per API key, team seats if multiple developers need access, and one dashboard instead of juggling individual Claude accounts. Full details are in /docs/streaming, and the shortest path to a working key is /docs/quickstart.
Production checklist
Before shipping a streaming chat feature, verify:
- Your Node process (or edge function) doesn't buffer the entire response before forwarding it to the client — if you're proxying through Express, disable response buffering and flush chunks as they arrive.
- Your frontend handles partial JSON gracefully if you're streaming structured output rather than plain text.
- You have a timeout and retry strategy for streams that stall without closing cleanly.
- Tool use (if you're combining it with streaming) is handled correctly — tool call deltas arrive as separate event types. See /docs/tools for that pattern.
questions
Does Claude's API support streaming for every model? Yes, streaming works the same way across Claude model variants by setting "stream": true in the request body — the SSE event structure doesn't change between models.
Can I stream and still get token usage counts? Yes. The final message_delta or message_stop event in the stream includes usage information, so you don't lose visibility into token counts just because you're streaming.
Why does my Node stream freeze instead of erroring out? This usually means a proxy or load balancer is silently dropping the idle connection. Check timeout settings on any infrastructure sitting between your Node server and the API, and confirm you're flushing chunks rather than buffering them.