← Blog

Claude API WebSocket Streaming Integration Guide

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

If you're looking for a wss:// endpoint on Claude's API, you won't find one. Anthropic's API — and SubToAPI's API, which sits on top of it — streams responses over plain HTTP using Server-Sent Events (SSE), not the WebSocket protocol. That's the first thing to understand before building anything: there is no native WebSocket handshake, no Upgrade header, no persistent bidirectional socket on the model provider's side.

What developers actually need when they search for "Claude API WebSocket streaming" is usually one of two things: either they want token-by-token streaming in a browser-based chat UI, or they're building a real-time app (a dashboard, a multiplayer tool, a live agent) where WebSocket is already the transport layer between their frontend and their own backend, and they need to pipe Claude's streamed output through it. Both are solvable — you just need a bridge pattern rather than a direct connection. This guide covers how to build that bridge correctly.

Why there's no native WebSocket support

SSE and WebSocket solve different problems. SSE is a one-way, server-to-client stream over a single HTTP request — exactly what you need for "the model is generating text, send me each chunk as it arrives." WebSocket is bidirectional and connection-oriented, which matters for things like live cursors or chat rooms, but it's unnecessary overhead for a one-shot generation request. Every major LLM provider — Anthropic, OpenAI, and others — streams via SSE for this reason. SubToAPI follows the same pattern on its /v1/messages endpoint, documented at /docs/streaming.

If your frontend architecture is already WebSocket-based, you don't connect your browser directly to Claude's streaming endpoint anyway — you shouldn't expose your API key client-side, full stop. You need a backend relay regardless. So the "WebSocket integration" is really about: backend receives SSE from the API, backend re-emits chunks over WebSocket to connected clients.

The bridge architecture

Browser (WebSocket client)
      │
      ▼
Your backend (WebSocket server)
      │  consumes SSE
      ▼
Claude API / SubToAPI streaming endpoint

Your server opens a streaming HTTP request to the Messages API, reads each SSE event as it arrives, and forwards the text delta to the connected WebSocket client. The browser never talks HTTP streaming at all — it just receives WebSocket messages.

Step 1: Stream from the API on your backend

Using Node.js and fetch against SubToAPI's streaming endpoint:

async function streamClaudeResponse(prompt, onChunk) {
  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-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();

    for (const line of lines) {
      if (!line.startsWith("data: ")) continue;
      const data = JSON.parse(line.slice(6));
      if (data.type === "content_block_delta") {
        onChunk(data.delta.text);
      }
    }
  }
}

Step 2: Relay chunks over WebSocket

Using the ws package for the WebSocket server:

import { WebSocketServer } from "ws";

const wss = new WebSocketServer({ port: 8080 });

wss.on("connection", (socket) => {
  socket.on("message", async (raw) => {
    const { prompt } = JSON.parse(raw.toString());

    await streamClaudeResponse(prompt, (chunk) => {
      socket.send(JSON.stringify({ type: "delta", text: chunk }));
    });

    socket.send(JSON.stringify({ type: "done" }));
  });
});

Step 3: Consume it on the client

const socket = new WebSocket("wss://your-backend.example.com");

socket.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.type === "delta") appendToUI(msg.text);
  if (msg.type === "done") finalizeMessage();
};

socket.onopen = () => {
  socket.send(JSON.stringify({ prompt: "Explain event loops in Node.js" }));
};

This gives you the real-time, incremental-rendering UX people associate with "WebSocket streaming," without needing the model provider to support WebSocket at all.

Things to get right

Backpressure. If your WebSocket client is slow to render, don't let the SSE reader buffer unbounded data in memory. Check socket.bufferedAmount before sending and throttle if it grows too large.

Reconnection. WebSocket connections drop. Design your protocol so a dropped connection mid-stream can be resumed or at least cleanly restarted — don't assume every token arrives.

One socket, many requests. If multiple users hit the same WebSocket server, make sure each connection handles its own stream independently. Don't share a single upstream SSE reader across sockets unless you're intentionally broadcasting the same generation to multiple viewers.

Auth stays server-side. Your API key — whether it's an Anthropic key or a SubToAPI sub_live_... key — should never reach the browser. The WebSocket layer exists partly to enforce that boundary. See /docs/quickstart for key setup and /docs/messages for the full request schema, including how tool use streams through content_block_delta events as described in /docs/tools.

Scaling. If you're running this at any real traffic, a single Node process holding open streaming connections works fine up to a point, but plan for horizontal scaling with a shared session store (Redis pub/sub is the common pattern) once you have more concurrent streams than one process can hold.

If you'd rather not manage key rotation, per-request logging, and rate limits yourself on top of this bridge, SubToAPI handles the application-key layer — issuing sub_live_... keys per app or team member, tracking usage, and exposing the same streaming Messages API you'd build against directly. Plans start at €9/month for solo use, with team and scale tiers at /pricing, and you can test the streaming endpoint from a free trial at /signup.

Questions

Does Claude's API support WebSocket directly? No. It streams via Server-Sent Events over HTTP. For a WebSocket-based frontend, you build a backend bridge that consumes the SSE stream and re-emits chunks to WebSocket clients.

Is SSE slower than WebSocket for streaming text generation? No meaningful difference for this use case. SSE is a one-way stream over a single HTTP connection and delivers tokens with the same latency characteristics — WebSocket's bidirectional capability just isn't needed for generation output.

Can I stream tool use results the same way? Yes. Tool use events arrive as additional SSE event types within the same stream, so your bridge logic forwards them identically — just distinguish content_block_delta text from tool-related event types in your relay code. See /docs/tools for the event shapes.

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 →