← Blog

Claude API Real-Time Chat Application: Build Guide

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

Building a real-time chat application with the Claude API means getting tokens to the browser as they're generated, not waiting for a full response before showing anything. The core pieces are: a streaming connection from Claude to your server, a way to push those chunks to the client (SSE or WebSockets), and client-side state management to render partial messages smoothly. This guide walks through the full stack, from the API call to the UI update loop.

If you've only used the Claude API for batch requests, the jump to real-time feels bigger than it is. You're not changing the model or the prompt — you're changing how the response is delivered and consumed. Get the streaming plumbing right once, and you can reuse it for every chat feature you build after.

Architecture overview

A real-time Claude chat app has three layers:

  1. Client — a chat UI that renders tokens as they arrive and manages conversation history.
  2. Server — a thin proxy that holds your API key, forwards requests to Claude, and relays the stream to the client.
  3. Claude API — generates the response with stream: true, sending incremental events instead of one blob.

Never call the Claude API directly from the browser. Your key would be exposed in network requests, and you lose control over rate limiting, logging, and cost tracking. The server layer is non-negotiable.

Step 1: Streaming from Claude

Claude's Messages API supports streaming via server-sent events when you set stream: true. Each event is a small JSON chunk — message_start, content_block_delta, message_delta, message_stop — and you append the delta.text fields as they arrive.

A minimal server-side streaming call looks like this:

const response = await fetch("https://api.anthropic.com/v1/messages", {
  method: "POST",
  headers: {
    "x-api-key": process.env.ANTHROPIC_API_KEY,
    "anthropic-version": "2023-06-01",
    "content-type": "application/json",
  },
  body: JSON.stringify({
    model: "claude-sonnet-4-20250514",
    max_tokens: 1024,
    stream: true,
    messages: [{ role: "user", content: userMessage }],
  }),
});

for await (const chunk of response.body) {
  // parse SSE lines, extract delta.text, forward to client
}

If you'd rather skip managing Anthropic SDK versions, rate limits, and billing dashboards yourself, SubToAPI exposes the same Messages API shape behind sub_live_... keys with streaming already wired up — see the streaming docs for the exact event format.

Step 2: Relaying the stream to the browser

Your backend needs to forward chunks to the client as they're received, not buffer them. The two common patterns:

Server-Sent Events (SSE) — simplest option, one-directional, works over plain HTTP, auto-reconnects in most browsers.

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 claudeStream = await callClaude(req.body.message);

  for await (const chunk of claudeStream) {
    res.write(`data: ${JSON.stringify(chunk)}\n\n`);
  }
  res.end();
});

WebSockets — bidirectional, better if users can interrupt or send messages mid-stream, or if you're building multi-user chat rooms where Claude responds to several participants.

For a single-user chat assistant, SSE is usually enough and simpler to deploy — no socket server to maintain, works fine behind most load balancers and CDNs.

Step 3: Client-side rendering

On the frontend, read the stream and append text incrementally:

const eventSource = new EventSource("/chat?message=" + encodeURIComponent(input));
let fullText = "";

eventSource.onmessage = (event) => {
  const chunk = JSON.parse(event.data);
  if (chunk.type === "content_block_delta") {
    fullText += chunk.delta.text;
    renderMessage(fullText);
  }
  if (chunk.type === "message_stop") {
    eventSource.close();
  }
};

Keep renderMessage cheap — on every chunk you're updating the DOM, so avoid re-parsing markdown on every token if the message is long. A common trick is to debounce markdown rendering to every 2–3 chunks and do a final full render on message_stop.

Step 4: Conversation state and context

Real-time chat apps need to track message history and send it back on every turn, since the Claude API is stateless between calls. Store the conversation as an array of {role, content} objects and append both the user message and the completed assistant response after each turn:

messages.push({ role: "user", content: userInput });
messages.push({ role: "assistant", content: fullText });

Watch your token budget as the conversation grows — long histories cost more per request and eventually hit context limits. Truncating or summarizing older turns is a separate concern worth handling before you ship, not after users complain about slow responses on turn 40.

Step 5: Handling tool calls in a live chat

If your chat app needs Claude to call functions — looking up data, running calculations — the streaming response will include tool-use blocks instead of plain text. Your server needs to detect these, pause the stream, execute the tool, and send the result back in a follow-up request before resuming the text stream to the client. This is the trickiest part of a real-time tool-using chat app; budget extra testing time for it. The tools documentation covers the request/response shape in detail.

Step 6: Production concerns

Before shipping, handle:

If you're building this for a team or a product with multiple contributors, SubToAPI's dashboard gives each person their own sub_live_... key with usage tracking per key, which makes debugging "whose request is spamming the API" much easier than sharing one raw Anthropic key across a codebase. Check pricing for Solo, Team, and Scale plans, or start with a free trial at signup.

Getting started quickly

If you want to skip the Anthropic account setup and SDK version juggling, the quickstart guide gets you from signup to a working streaming request in a few minutes, and the Messages API reference documents every parameter you'll need for a production chat app.

Questions

Do I need WebSockets for a Claude chat app, or is SSE enough? SSE is enough for most single-user chat UIs — it's simpler to deploy and handles one-directional streaming well. Use WebSockets only if you need bidirectional communication, like letting users interrupt a response mid-generation or building multi-participant rooms.

How do I keep conversation context across turns? The Claude API is stateless — you must resend the full message history (or a trimmed/summarized version of it) with every request. Store messages in an array on your server or client and append both the user and assistant turns after each exchange.

Can I call the Claude API directly from the browser for a chat app? No. Doing so exposes your API key in network requests. Always route requests through a backend you control, which also lets you add rate limiting, logging, and usage tracking per user.

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 →