← Blog

How to Stream Claude API Responses in Node.js

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

Streaming lets your Node.js app display Claude's output token by token instead of waiting for the full response. This matters for chat UIs, CLIs, and any product where users expect to see text appear progressively rather than staring at a loading spinner for 10+ seconds on a long generation.

The short answer: Claude's API streams responses as Server-Sent Events (SSE). In Node.js you consume that stream either with the official Anthropic SDK (which handles parsing for you), or manually with fetch and a readable stream reader if you want full control over the event loop. Below are both approaches, plus what changes if you're calling Claude through a proxy like SubToAPI instead of Anthropic directly.

Streaming with the Anthropic SDK

The simplest path is the official @anthropic-ai/sdk package. It exposes a .stream() helper that returns an async iterable of parsed events.

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

async function streamResponse() {
  const stream = client.messages.stream({
    model: "claude-sonnet-4-5",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Explain event loops in Node.js" }],
  });

  stream.on("text", (text) => {
    process.stdout.write(text);
  });

  const finalMessage = await stream.finalMessage();
  console.log("\n\nUsage:", finalMessage.usage);
}

streamResponse();

The on("text") listener fires for every incremental text delta. finalMessage() resolves once the stream closes and gives you the complete assembled message, including token usage — useful for logging cost per request.

Streaming manually with fetch and SSE parsing

If you're not using the SDK — maybe you're in an edge runtime, a serverless function with size constraints, or you just want to understand what's happening under the hood — you can parse the raw SSE stream yourself.

async function streamClaude(prompt) {
  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: 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 lines = buffer.split("\n");
    buffer = lines.pop(); // keep incomplete line for next chunk

    for (const line of lines) {
      if (!line.startsWith("data:")) continue;
      const data = line.slice(5).trim();
      if (data === "[DONE]") return;

      const event = JSON.parse(data);
      if (event.type === "content_block_delta") {
        process.stdout.write(event.delta.text ?? "");
      }
    }
  }
}

streamClaude("Write a haiku about distributed systems");

Key things this handles correctly: SSE events can span multiple chunks, so you buffer partial lines until you hit a newline. You also need to filter by event type since the stream emits several event kinds (message_start, content_block_start, content_block_delta, message_delta, message_stop) and only content_block_delta carries the text you usually want to render.

Streaming over HTTP to your frontend

If Node.js is your backend and you want to relay the stream to a browser, the cleanest pattern is to pipe SSE straight through using Express or a framework route handler:

app.post("/chat", async (req, res) => {
  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Cache-Control", "no-cache");
  res.setHeader("Connection", "keep-alive");

  const stream = client.messages.stream({
    model: "claude-sonnet-4-5",
    max_tokens: 1024,
    messages: req.body.messages,
  });

  stream.on("text", (text) => {
    res.write(`data: ${JSON.stringify({ text })}\n\n`);
  });

  stream.on("end", () => res.end());
  stream.on("error", () => res.end());
});

Your frontend then reads this with EventSource or a fetch reader, same pattern as above, just one hop further down the chain.

Where SubToAPI fits in

If you're already paying for Claude through a Pro or Max plan rather than a pay-as-you-go Anthropic API account, you don't have direct API access to run the code above. SubToAPI turns that subscription into a normal HTTPS API with its own key (sub_live_...), so the same streaming code works — you just point it at https://api.subtoapi.app/v1/messages and swap the header:

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: "Explain event loops in Node.js" }],
  }),
});

The SSE parsing loop is identical — SubToAPI passes through the same event format, so everything in the manual streaming example above works unchanged. This is useful if you want to prototype streaming in a side project without committing to usage-based API billing. See the quickstart and streaming docs for the full event reference, or check pricing if you're comparing it against a metered API account.

Common mistakes to avoid

questions

Does streaming cost more than non-streaming requests? No. Token pricing is identical whether you stream or wait for the full response. Streaming only changes delivery timing, not billing.

Can I stream tool use (function calling) responses the same way? Yes, but tool call arguments arrive as partial JSON deltas across multiple content_block_delta events. You need to accumulate the fragments and parse the full JSON only once the content block closes — see the tool use docs for the exact event shape.

What's the difference between the SDK's .stream() and calling the REST endpoint directly? The SDK parses SSE events for you and exposes convenience listeners like on("text"), while the raw REST endpoint just returns the SSE stream — you write the parsing loop yourself. Both consume the same underlying API and produce identical output.

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 →