← Blog

Claude API Real-Time Chat App Tutorial

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

Building a real-time chat app with Claude means streaming tokens from the model to the browser as they're generated, instead of waiting for a full response and dumping it on screen. That's the difference between a chat UI that feels alive and one that feels like a form submission. This tutorial walks through the actual architecture: a backend endpoint that calls Claude with streaming enabled, a frontend that consumes Server-Sent Events, and the conversation state management that keeps multi-turn chat coherent.

You don't need a WebSocket server to pull this off. Server-Sent Events (SSE) over a normal HTTP connection handle one-directional token streaming fine, and they're far simpler to deploy and debug than a full WebSocket stack. We'll use that approach throughout.

Architecture overview

A real-time Claude chat app has three moving parts:

  1. Frontend — captures user input, renders streamed tokens as they arrive, maintains the visible conversation
  2. Backend — holds the API key, forwards the request to Claude, pipes the streamed response back to the client
  3. State store — the message history sent with each request, since Claude's API is stateless between calls

Never call the Claude API directly from browser JavaScript — your API key would be exposed to anyone who opens dev tools. The backend proxy step is non-negotiable for a production chat app.

Step 1: Set up API access

Get an API key from your Claude access provider. If you're using SubToAPI, sign up and grab a key (sub_live_...) from the dashboard — it works as a drop-in HTTPS endpoint with streaming, tool use, and per-key usage tracking already built in, which saves you from building that tracking layer yourself. The quickstart covers key creation in under five minutes.

Step 2: Build the streaming backend endpoint

Here's a minimal Node/Express endpoint that streams a Claude response to the client using SSE:

import express from "express";
const app = express();
app.use(express.json());

app.post("/chat/stream", async (req, res) => {
  const { messages } = req.body;

  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-5",
      max_tokens: 1024,
      stream: true,
      messages
    })
  });

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

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

  res.end();
});

app.listen(3000);

This endpoint keeps the API key server-side, forwards the chat history, and relays the raw SSE chunks straight through to the browser without buffering the whole response first. Details on event types and chunk structure are in the streaming docs.

Step 3: Consume the stream on the frontend

The browser side listens for data chunks and appends text to the UI as it arrives:

async function sendMessage(messages, onToken) {
  const res = await fetch("/chat/stream", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ messages })
  });

  const reader = res.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 payload = line.slice(5).trim();
      if (payload === "[DONE]") return;

      try {
        const event = JSON.parse(payload);
        if (event.type === "content_block_delta") {
          onToken(event.delta.text);
        }
      } catch {}
    }
  }
}

Hook onToken up to append text to a message bubble in your component state, and you've got tokens appearing live as Claude generates them.

Step 4: Manage conversation state

Claude's API has no memory between requests — every call needs the full message history. A minimal state shape looks like this:

let conversation = [
  { role: "user", content: "What's the capital of Portugal?" },
  { role: "assistant", content: "Lisbon." },
  { role: "user", content: "And its population?" }
];

After each exchange, append the user's new message and the assistant's completed response to this array before the next call. Watch two things as conversations grow:

Step 5: Add tool use (optional but common)

Real-time chat apps often need Claude to call functions — looking up order status, querying a database, running a calculation — mid-conversation. The flow is the same streaming setup, but you handle tool_use content blocks in the response, execute the function server-side, and send the result back as a tool_result message before continuing the stream. The tool use docs cover the schema and request/response shape in detail.

Production considerations

A tutorial demo and a shipped product diverge on a few points:

SubToAPI handles key issuance, streaming, and usage metadata out of the box, so if you're building this for a team or a product with multiple users, it removes a chunk of the plumbing above. Plans start at €9/month on the Solo tier, with team seats on the Team (€19/seat) and Scale (€49/seat) plans — see pricing for details.

Questions

Do I need WebSockets to stream Claude responses? No. SSE over standard HTTP works fine for one-directional token streaming and is much simpler to deploy, since it rides on normal HTTP infrastructure without a persistent bidirectional connection.

Can I call the Claude API directly from the browser? You can technically make the request, but you should never do this in production — it exposes your API key to anyone inspecting network traffic. Always proxy through a backend you control.

How do I keep conversation context across multiple messages? Store the full message history (user and assistant turns) in your own state and send it with every request, since the API itself doesn't retain memory between calls. Trim or summarize history once it grows large to stay within context limits.

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 →