Claude API Real-Time Chat Application Tutorial
What "real-time chat" means with the Claude API
If you're building a chat application on top of Claude, "real-time" almost always means streaming tokens as they're generated rather than waiting for a full response and dumping it on screen. The Claude API supports this natively through server-sent events (SSE), and this tutorial walks through the full setup: backend proxy, streaming endpoint, frontend rendering, and message history management.
By the end you'll have a working chat loop: user sends a message, the UI shows a typing indicator, text streams in token by token, and the conversation state persists for the next turn. We'll use plain JavaScript and fetch/curl examples so you can adapt it to any framework.
Architecture overview
A real-time Claude chat app has three layers:
- Frontend — renders messages, handles streaming chunks, manages input state.
- Backend proxy — holds your API key, forwards requests, never exposes credentials to the browser.
- Claude API (or a gateway in front of it) — does the actual generation and streaming.
You never call the Claude API directly from browser JavaScript — that leaks your key to anyone who opens dev tools. The backend proxy is non-negotiable for production apps.
If you don't want to build and maintain that proxy layer yourself — handling retries, timeouts, key rotation, per-user metering — a hosted layer like SubToAPI gives you an HTTPS endpoint with its own scoped API keys (sub_live_...), so your frontend team can integrate against a stable contract while usage and billing are tracked per key.
Step 1: Set up the streaming endpoint
On the backend, you make a request with stream: true and read the response as a stream of server-sent events instead of a single JSON blob.
curl -N https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"stream": true,
"messages": [
{"role": "user", "content": "Explain WebSockets in two sentences."}
]
}'
The response comes back as a series of event: / data: lines, with content_block_delta events carrying incremental text chunks. Your server needs to parse these and forward them to the client — usually as its own SSE stream or over a WebSocket.
Step 2: Build the backend proxy (Node example)
import express from "express";
const app = express();
app.use(express.json());
app.post("/api/chat", async (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
const upstream = 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-3-5-sonnet-20241022",
max_tokens: 1024,
stream: true,
messages: req.body.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 is the minimal version. In production you'd add authentication on /api/chat, request validation, and timeout handling so a dropped connection doesn't leave a hanging process.
If you're using SubToAPI instead of calling Anthropic directly, the shape stays almost identical — you swap the endpoint and auth header:
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-3-5-sonnet-20241022",
max_tokens: 1024,
stream: true,
messages: req.body.messages,
}),
});
Full details on the streaming contract are in the streaming docs and the general messages reference.
Step 3: Render streaming text in the frontend
On the client, consume the SSE stream and append each chunk to the current message as it arrives:
async function sendMessage(messages) {
const res = await fetch("/api/chat", {
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);
const lines = buffer.split("\n");
buffer = lines.pop();
for (const line of lines) {
if (!line.startsWith("data:")) continue;
const payload = JSON.parse(line.slice(5));
if (payload.type === "content_block_delta") {
appendToCurrentMessage(payload.delta.text);
}
}
}
}
appendToCurrentMessage is your UI update function — in React you'd update state, in a vanilla app you'd mutate a DOM node directly. The key detail: update the UI on every chunk, not just at the end, or you lose the "real-time" feel entirely.
Step 4: Manage conversation history
Claude is stateless between requests — every call needs the full message history. For a chat app, keep an array of {role, content} objects and append both the user's message and the assistant's completed response after each turn:
const history = [];
function addUserMessage(text) {
history.push({ role: "user", content: text });
}
function addAssistantMessage(text) {
history.push({ role: "assistant", content: text });
}
Send the whole history array on each request. For long-running conversations, watch your token usage — trim or summarize older turns once you approach the model's context window, otherwise latency and cost both creep up.
Step 5: Handle disconnects and errors
Real-time apps need to handle the unhappy path: users closing tabs mid-stream, network drops, or the model returning an error partway through generation. Three things matter:
- Abort on unmount — use an
AbortControllertied to component lifecycle so you don't leak open connections. - Partial message recovery — if a stream cuts off, save what was received so far rather than discarding it.
- Retry with backoff — transient network errors should trigger a retry, not an immediate failure shown to the user.
Getting started quickly
If you'd rather skip building the proxy layer from scratch, SubToAPI turns your existing Claude access into an HTTPS API with streaming, tool use, and usage metadata out of the box. Create an application key, point your chat app at it, and you get the same streaming contract shown above without running your own backend. Plans start at €9/month for solo use, with team seats at €19 and €49 for scale, and a free trial at signup. See the quickstart for the fastest path to a working integration.
Questions
Does the Claude API support WebSockets for chat? No — Claude's native API uses HTTP with server-sent events for streaming, not WebSockets. You can wrap SSE in a WebSocket on your own backend if your frontend architecture requires it, but the upstream connection to Claude is SSE-based.
Why does my streamed text appear in bursts instead of smoothly? This is usually a frontend buffering issue, not an API problem — check that you're writing each chunk to the DOM/state immediately rather than batching updates, and confirm your proxy isn't buffering the response before forwarding it.
How do I keep conversation context across multiple chat turns? Store the full message history client- or server-side and send the complete array with every request — Claude doesn't retain state between calls, so omitting prior turns will cause the model to lose context immediately.