← Blog

Claude API Node.js Streaming Example

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

Streaming lets your Node.js app display Claude's response as it's generated, instead of waiting for the full reply. This matters for chat UIs, CLI tools, and anything where a user is staring at a blank screen waiting for tokens. Below is a complete, working example of streaming Claude responses in Node.js, plus the patterns you need to handle it correctly in production.

The short answer: Claude's API uses Server-Sent Events (SSE) for streaming. In Node.js, you consume this by making a POST request with "stream": true in the body, then reading the response body as a stream of event:/data: lines. You parse each JSON chunk and append text deltas as they arrive. No special SDK is required — fetch with a readable stream works fine on Node 18+.

Basic Streaming Example

Here's a minimal script using native fetch (Node 18+) against the Anthropic Messages API format:

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-sonnet-4-5",
    max_tokens: 1024,
    stream: true,
    messages: [{ role: "user", content: "Write a haiku about streaming APIs" }],
  }),
});

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);
    }
  }
}

This works, but every team re-implements this buffer-splitting logic slightly differently, and it's easy to drop a chunk boundary or mishandle partial JSON. If you're already paying for Claude access through a subscription rather than the raw Anthropic API, SubToAPI (https://subtoapi.app) exposes the same SSE streaming contract over a plain HTTPS endpoint, so this exact code pattern works against https://api.subtoapi.app/v1/messages with an Authorization: Bearer $SUBTOAPI_KEY header instead of an x-api-key.

Streaming with SubToAPI

If you're using SubToAPI to turn your Claude subscription into an API key, the streaming call looks nearly identical:

const response = await fetch("https://api.subtoapi.app/v1/messages", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
  },
  body: JSON.stringify({
    model: "claude-sonnet-4-5",
    max_tokens: 1024,
    stream: true,
    messages: [{ role: "user", content: "Summarize this in 3 bullet points" }],
  }),
});

// same reader/decoder loop as above

Full request/response shapes and event types are documented at /docs/streaming, with the base request format covered in /docs/messages. If you're new to the API entirely, start with /docs/quickstart.

Handling the Event Types

A streamed Claude response emits several event types in order, and your parser should branch on event.type:

A more robust handler looks like this:

function handleEvent(event) {
  switch (event.type) {
    case "content_block_delta":
      if (event.delta.type === "text_delta") {
        process.stdout.write(event.delta.text);
      }
      break;
    case "message_delta":
      if (event.delta.stop_reason) {
        console.log("\nStopped:", event.delta.stop_reason);
      }
      break;
    case "message_stop":
      console.log("\nDone.");
      break;
  }
}

Wire this into the same reader loop by calling handleEvent(event) instead of the inline if.

Streaming with Tool Use

Streaming gets slightly more involved when Claude calls a tool mid-response, since tool inputs arrive as partial JSON across multiple content_block_delta events with type: "input_json_delta". You need to accumulate the string fragments and JSON.parse only once the block closes:

let toolInputBuffer = "";

function handleEvent(event) {
  if (event.type === "content_block_delta" && event.delta.type === "input_json_delta") {
    toolInputBuffer += event.delta.partial_json;
  }
  if (event.type === "content_block_stop" && toolInputBuffer) {
    const toolInput = JSON.parse(toolInputBuffer);
    console.log("Tool call ready:", toolInput);
    toolInputBuffer = "";
  }
}

See /docs/tools for the full tool-use request format and how tool results get fed back into the conversation.

Common Mistakes to Avoid

Splitting on the wrong boundary. SSE chunks don't align with network packets — you must buffer by newline, not assume one data: line per read() call, as shown above with the buffer.split("\n") pattern.

Forgetting [DONE] or malformed lines. Always check line.startsWith("data: ") before parsing, and skip empty lines — they're used as SSE separators.

Not handling connection drops. Streaming requests held open for 30+ seconds can hit proxy or load balancer timeouts. Wrap the fetch in a retry with exponential backoff, and consider setting max_tokens conservatively if you're seeing truncated streams.

Blocking the event loop. If you're writing streamed text into a WebSocket to a browser client, avoid synchronous JSON stringify/parse on large tool payloads inside a hot loop — batch writes where possible.

When Streaming Isn't Worth It

For backend jobs — summarization pipelines, batch classification, report generation — you usually don't need streaming at all. Just set "stream": false and wait for the full response. Streaming adds complexity that only pays off when a human is watching the output in real time. For comparing plan limits and request quotas if you're deciding between direct Anthropic access and a subscription-based API like SubToAPI, see /pricing.

FAQ

Does Claude's Node.js streaming use WebSockets? No. It uses HTTP with Server-Sent Events (SSE) over a single long-lived response stream, not WebSockets. You read the response body incrementally with a standard ReadableStream reader.

Can I use the official Anthropic SDK instead of raw fetch? Yes — the @anthropic-ai/sdk package has a built-in messages.stream() helper that handles buffering and event parsing for you. The raw fetch approach above is useful when you need full control or are hitting a compatible endpoint without the SDK installed.

Why does my stream cut off before the response finishes? This is almost always a max_tokens limit being hit, a proxy timing out the connection, or a client-side reader that stops before message_stop fires. Check the stop_reason in the final message_delta event to confirm which case applies.

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 →