← Blog

Claude API Node.js Streaming Implementation Guide

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

Streaming lets your Node.js app display Claude's response token-by-token instead of waiting for the full completion, which matters a lot for chat UIs, CLIs, and anything where perceived latency affects user experience. The core implementation pattern is the same whether you're calling Claude directly or through a proxy: open an HTTP connection with streaming enabled, read the response body as a stream of Server-Sent Events (SSE), parse each event, and forward the text deltas to your frontend or terminal as they arrive.

This guide walks through a working Node.js implementation — from a raw fetch approach using the native streams API, to handling backpressure and errors, to wiring it into an Express route that proxies the stream to a browser client over SSE.

Why Stream in Node.js at All

Without streaming, a Node.js backend calling Claude blocks on the full response before sending anything back. For a 2,000-token answer that can mean 10-20 seconds of silence on the client. Streaming fixes this by letting you flush partial output to the client as soon as it's available, which is why almost every production chat interface uses it.

The tricky part isn't calling the streaming endpoint — it's correctly parsing SSE chunks that may arrive split across multiple TCP packets, and propagating backpressure so you don't buffer unbounded memory if the client is slow to consume.

Basic Streaming with Fetch and Async Iterators

Node 18+ ships with a native fetch whose response.body is a ReadableStream. You can consume it with a simple async loop:

async function streamCompletion(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-sonnet-4',
      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 in buffer

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

      try {
        const event = JSON.parse(data);
        if (event.type === 'content_block_delta') {
          process.stdout.write(event.delta?.text ?? '');
        }
      } catch {
        // ignore partial JSON, it'll complete on next chunk
      }
    }
  }
}

The key detail here is the buffer.split('\n') / buffer.pop() pattern. SSE chunks don't respect line boundaries, so you must hold back the last (possibly incomplete) line and prepend it to the next chunk. Skipping this step is the most common bug in hand-rolled streaming clients.

Handling Backpressure Properly

If you're piping the stream into something slower than network speed — writing to disk, pushing to a websocket with a full buffer, or running expensive per-token processing — use Node's Writable stream interface instead of a flat loop, so backpressure signals propagate automatically:

import { Writable } from 'stream';
import { Readable } from 'stream';

function streamToWritable(responseBody, writable) {
  const nodeStream = Readable.fromWeb(responseBody);
  return new Promise((resolve, reject) => {
    nodeStream.pipe(writable);
    nodeStream.on('end', resolve);
    nodeStream.on('error', reject);
  });
}

Readable.fromWeb (Node 17+) converts the web-standard ReadableStream into a classic Node Readable, letting you .pipe() it anywhere — including directly into an HTTP response if you're building a proxy endpoint.

Proxying a Stream to the Browser with Express

A common pattern is a Node backend that holds the API key and streams results to a browser client via SSE:

import express from 'express';

const app = express();
app.use(express.json());

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 upstream = 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-sonnet-4',
      max_tokens: 1024,
      stream: true,
      messages: req.body.messages
    })
  });

  const reader = upstream.body.getReader();
  const decoder = new TextDecoder();

  req.on('close', () => reader.cancel());

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    res.write(decoder.decode(value, { stream: true }));
  }

  res.end();
});

app.listen(3000);

Note req.on('close', () => reader.cancel()) — this cancels the upstream read if the browser tab closes mid-stream, so you don't keep paying for tokens no one is reading.

Error Handling and Reconnection

Streaming connections can drop mid-response due to network blips or server-side timeouts. Wrap the stream consumption in a retry layer that tracks how much content was already emitted, so a reconnect doesn't duplicate output:

async function streamWithRetry(prompt, onToken, maxRetries = 2) {
  let attempt = 0;
  while (attempt <= maxRetries) {
    try {
      await streamCompletion(prompt, onToken);
      return;
    } catch (err) {
      attempt++;
      if (attempt > maxRetries) throw err;
      await new Promise(r => setTimeout(r, 500 * attempt));
    }
  }
}

For most apps, full idempotent resume isn't worth the complexity — a clean retry of the whole request is usually fine since Claude responses are fast enough that users won't notice a 1-2 second restart.

Using a Managed Endpoint Instead

If you'd rather not maintain SSE parsing, buffering, and reconnection logic yourself, SubToAPI exposes Claude through a standard streaming HTTPS endpoint with the same request shape shown above — you just point fetch at https://api.subtoapi.app/v1/messages with your sub_live_... key. It handles usage metadata, tool-use events, and team-level API keys so you can issue separate credentials per environment or per teammate without sharing a single Claude login. See the streaming docs and messages API reference for the full event schema, or the quickstart to get a key in a few minutes. Plans start at €9/month with a free trial — check pricing for Team and Scale tiers if you need multiple seats.

Questions

Does Claude's streaming API use Server-Sent Events? Yes. Streaming responses are delivered as SSE with data: lines containing JSON events like content_block_delta, which carry incremental text chunks you decode and append on the client.

Can I use streaming with Node's older http module instead of fetch? Yes — http.request gives you a response object that's already a readable stream; you consume it with .on('data') events and apply the same line-buffering logic described above.

How do I cancel a stream early in Node.js? Call reader.cancel() on the ReadableStream reader, or .destroy() on a Node Readable. Always do this when the client disconnects to avoid wasting tokens on output nobody will see.

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 →