← Blog

Claude API WebSocket Integration Example

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

If you're looking for a Claude API WebSocket integration example, the first thing to know is that Anthropic's Claude API does not expose a native WebSocket endpoint. It's a standard HTTPS API that supports Server-Sent Events (SSE) for streaming responses token by token. Any "Claude API WebSocket" setup you see in production is actually a WebSocket layer that a developer built on top of the HTTP/SSE API, not a direct protocol Anthropic ships.

This matters because it changes how you architect your app. If you need real-time, bidirectional communication with browser clients (chat UIs, collaborative tools, live dashboards), you build a small server that holds the WebSocket connection to the client and forwards requests to Claude's HTTP API, relaying the SSE stream back over the socket. Below is a complete, working example of that pattern, plus the reasoning for when you actually need it versus when plain SSE is enough.

Why Claude doesn't need WebSockets (usually)

WebSockets are built for bidirectional, low-latency, many-small-messages communication — multiplayer games, live cursors, trading tickers. A Claude completion is fundamentally one request producing one streamed response. SSE over HTTP already gives you:

So if your use case is "user sends a prompt, Claude streams back an answer," you don't need WebSockets at all — SSE is simpler and works with any HTTP infrastructure (load balancers, serverless functions, CDNs) without special handling.

You do want a WebSocket layer when:

The architecture

Browser (WebSocket) <--> Your Node server <--> Claude API (HTTPS/SSE)

Your server is the bridge. It accepts a WebSocket connection, receives a user message, opens a streaming HTTP request to the Claude API, and forwards each chunk back down the socket as it arrives.

Server: Node.js WebSocket proxy

import { WebSocketServer } from "ws";
import fetch from "node-fetch";

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

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

    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-3-5-sonnet-20241022",
        max_tokens: 1024,
        stream: true,
        messages: [{ role: "user", content: prompt }],
      }),
    });

    for await (const chunk of response.body) {
      const lines = chunk.toString().split("\n").filter(Boolean);
      for (const line of lines) {
        if (line.startsWith("data: ")) {
          const payload = line.slice(6);
          if (payload === "[DONE]") continue;
          socket.send(payload);
        }
      }
    }

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

Client: browser WebSocket consumer

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

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

socket.onmessage = (event) => {
  const data = JSON.parse(event.data);
  if (data.type === "content_block_delta") {
    appendToUI(data.delta.text);
  }
  if (data.type === "done") {
    console.log("stream finished");
  }
};

This is the shape of nearly every "Claude API WebSocket integration" you'll find in the wild: a thin proxy that terminates the socket on your side and re-emits SSE events as WebSocket messages.

Where this gets painful

The proxy pattern works, but you own all the operational overhead:

None of this is Claude-specific — it's the standard cost of running your own real-time infrastructure. If your product doesn't strictly need bidirectional push, it's usually faster to skip WebSockets entirely and let the client call a streaming HTTP endpoint directly.

This is where SubToAPI fits if you're already paying for Claude access and want a clean HTTPS layer without managing Anthropic SDK versions, key storage, or usage accounting yourself. SubToAPI turns your Claude access into an HTTPS API with its own scoped sub_live_... keys, so your WebSocket proxy (or your regular backend) talks to one stable endpoint instead of juggling Anthropic credentials directly. Streaming responses, tool use, and per-key usage metadata are available out of the box — see /docs/streaming and /docs/tools for the request formats, and /docs/messages for the base completion API. You can drop the same fetch call from the example above into your proxy, just pointed at https://api.subtoapi.app/v1/messages with Authorization: Bearer $SUBTOAPI_KEY, and get team-level usage tracking without writing your own billing logic.

If you want to start without touching infrastructure at all, sign up at /signup, grab an API key, and check /docs/quickstart — the free trial is enough to test a WebSocket proxy end-to-end before committing to a plan on /pricing.

Practical checklist before you build one

  1. Confirm you actually need bidirectional push — most chat UIs don't
  2. Decide whether reconnection logic lives client-side or server-side
  3. Never pass raw Anthropic (or SubToAPI) keys to the browser — the proxy holds the key, the client only holds a session token
  4. Buffer tool-use JSON deltas before parsing; partial chunks will not be valid JSON mid-stream
  5. Log usage fields from each response so you can attribute cost per socket session

questions

Does the Claude API support WebSockets natively? No. Claude's API is HTTPS with SSE streaming. Any WebSocket integration is a proxy you build that forwards SSE chunks over a socket connection.

When should I use WebSockets instead of SSE for Claude responses? Only when your frontend already needs a persistent bidirectional channel — for multiplayer apps, live collaboration, or sessions where the client sends interrupts mid-stream. Otherwise plain SSE is simpler and scales better.

Can I use SubToAPI inside a WebSocket proxy? Yes. Point your proxy's fetch calls at the SubToAPI streaming endpoint instead of Anthropic directly — see /docs/streaming — and you get usage metadata and team key management without extra code.

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 →