← Blog

Claude API WebSocket Streaming for Chat UIs

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

If you're searching for "Claude API WebSocket streaming chat UI," you've probably noticed something confusing while building a real-time chat interface: Claude's API doesn't actually offer a WebSocket endpoint. It streams responses over plain HTTP using server-sent events (SSE). That's not a limitation — it's the right tool for a one-way token stream — but it means you need a small architectural layer if your frontend talks to your backend over WebSocket (which is common in chat apps built with Socket.io, native WebSocket, or frameworks like Phoenix Channels).

This article covers exactly how to bridge that gap: how Claude's streaming actually works, how to relay it through a WebSocket connection to your chat UI, and when you should skip WebSocket entirely and just stream SSE straight to the browser.

Why Claude doesn't use WebSocket

WebSocket is built for bidirectional, persistent connections — useful for chat apps, multiplayer games, or live collaboration where both sides send messages continuously. Claude's API response pattern is simpler: you send one request, and the model streams back tokens as they're generated. That's a textbook SSE use case — a single long-lived HTTP response with a unidirectional flow of chunks.

SSE gives you:

So "Claude API WebSocket streaming" in the literal sense doesn't exist — but building a WebSocket-based chat UI that displays Claude's streamed tokens in real time absolutely does, and it's a common pattern when your app already uses WebSocket for presence, typing indicators, or multi-user chat rooms.

The architecture: WebSocket chat UI + SSE backend

The pattern is straightforward:

  1. Browser opens a WebSocket connection to your server.
  2. User sends a message over that WebSocket.
  3. Your server makes a streaming HTTP request to Claude (or a Claude-compatible API).
  4. As SSE chunks arrive from Claude, your server forwards each token to the browser over the same WebSocket.
  5. The browser appends tokens to the chat bubble as they arrive.

This keeps your frontend's connection model consistent (one WebSocket for everything) while letting the backend handle the SSE parsing that Claude's API actually speaks.

Server: relaying the stream

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

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

wss.on("connection", (ws) => {
  ws.on("message", async (data) => {
    const { message } = JSON.parse(data.toString());

    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: message }],
      }),
    });

    const reader = response.body;
    for await (const chunk of reader) {
      const text = chunk.toString();
      for (const line of text.split("\n")) {
        if (line.startsWith("data:")) {
          const payload = line.slice(5).trim();
          if (payload === "[DONE]") continue;
          ws.send(JSON.stringify({ type: "token", data: payload }));
        }
      }
    }

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

This is intentionally simplified SSE parsing — in production, buffer partial lines across chunk boundaries rather than splitting naively on every \n.

Client: a minimal WebSocket chat UI

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

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);

  if (msg.type === "token") {
    const parsed = JSON.parse(msg.data);
    const text = parsed.delta?.text || "";
    currentBubble += text;
    renderChatBubble(currentBubble);
  }

  if (msg.type === "done") {
    finalizeChatBubble(currentBubble);
    currentBubble = "";
  }
};

function sendMessage(text) {
  ws.send(JSON.stringify({ message: text }));
}

The user sees tokens appear incrementally, exactly like the native Claude web interface, but through infrastructure your existing WebSocket-based app already understands.

Using SubToAPI for the streaming layer

If you're building this chat UI on top of your own Claude access, SubToAPI turns that access into a standard HTTPS API with proper streaming support, so the relay server above works without any custom auth plumbing. You get:

See the streaming docs and the quickstart for the exact request/response shapes, or check messages API reference for the full payload structure. Plans start at Solo for solo projects, with Team and Scale tiers for shared seats — details on pricing, and you can try it with a free trial at signup.

When to skip WebSocket entirely

If your chat UI doesn't need WebSocket for anything else (no presence, no multi-user rooms, no server-push outside of the chat response itself), don't add the complexity. Use EventSource or fetch with a streaming body directly against the Claude-compatible endpoint from the browser, or proxy through a simple HTTP streaming endpoint on your server. WebSocket adds connection management overhead (reconnects, heartbeat, backpressure) that SSE handles for you automatically in a single-direction chat flow.

Reach for the WebSocket relay pattern specifically when:

questions

Does the Claude API support native WebSocket streaming? No. Claude's API streams responses using server-sent events (SSE) over standard HTTP. To display that stream inside a WebSocket-based chat UI, your backend relays SSE chunks to the browser over the WebSocket connection.

Is WebSocket faster than SSE for streaming Claude responses? Not meaningfully. Both delay is dominated by model generation speed, not transport. WebSocket is worth using only when your app needs bidirectional or multi-client messaging beyond the Claude response itself.

Can I stream Claude responses directly to the browser without a backend relay? Yes, if you don't need to hide your API key or add a WebSocket layer — use fetch with a streaming response body or EventSource directly against a Claude-compatible streaming endpoint like /v1/messages.

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 →