Claude API React Chatbot Tutorial
Building a chatbot with React and the Claude API means solving three problems at once: calling the API without exposing your key in the browser, streaming tokens into the UI as they arrive, and managing conversation state across turns. This tutorial walks through all three with a working component you can drop into an existing app.
We'll build a minimal chat UI backed by a proxy endpoint, add streaming so responses appear word-by-word instead of all at once, and handle the common failure modes (rate limits, network drops, long responses). By the end you'll have a chatbot that feels responsive and doesn't leak credentials to the client.
Why you can't call Claude directly from the browser
Claude API keys are meant to be used server-side. If you put your key in client-side JavaScript, anyone who opens devtools can steal it and run up your bill. The standard pattern is:
- React frontend sends the user's message to your own backend (an API route, Express endpoint, or serverless function).
- Your backend calls Claude (or a gateway like SubToAPI) with the real key, stored as an environment variable.
- The response — or a stream of chunks — is relayed back to the frontend.
This tutorial uses a small Node/Express proxy, but the same pattern works with Next.js API routes, Cloudflare Workers, or any backend runtime.
Setting up the backend proxy
// server.js
import express from "express";
import cors from "cors";
const app = express();
app.use(cors());
app.use(express.json());
app.post("/api/chat", 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 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-opus-4-20250514",
max_tokens: 1024,
messages,
stream: true,
}),
});
for await (const chunk of response.body) {
res.write(chunk);
}
res.end();
});
app.listen(3001);
If you're already using SubToAPI to manage your Claude access, swap the endpoint and headers for your sub_live_... key:
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
},
body: JSON.stringify({
model: "claude-opus-4-20250514",
max_tokens: 1024,
messages,
stream: true,
}),
});
This is useful once you have multiple team members or apps calling Claude — you get one dashboard for usage across all of them instead of juggling raw Anthropic keys. See /docs/streaming for the full streaming reference.
The React chat component
The frontend needs three pieces of state: the message history, the current input, and whether a response is streaming.
import { useState, useRef } from "react";
export default function Chatbot() {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState("");
const [streaming, setStreaming] = useState(false);
const bottomRef = useRef(null);
async function sendMessage() {
if (!input.trim()) return;
const userMessage = { role: "user", content: input };
const nextMessages = [...messages, userMessage];
setMessages(nextMessages);
setInput("");
setStreaming(true);
const assistantIndex = nextMessages.length;
setMessages([...nextMessages, { role: "assistant", content: "" }]);
const res = await fetch("http://localhost:3001/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages: nextMessages }),
});
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 data = line.slice(6);
if (data === "[DONE]") continue;
try {
const parsed = JSON.parse(data);
if (parsed.type === "content_block_delta") {
const text = parsed.delta?.text || "";
setMessages((prev) => {
const updated = [...prev];
updated[assistantIndex] = {
...updated[assistantIndex],
content: updated[assistantIndex].content + text,
};
return updated;
});
}
} catch {
// incomplete JSON chunk, wait for more data
}
}
}
setStreaming(false);
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
}
return (
<div style={{ maxWidth: 600, margin: "0 auto" }}>
<div style={{ height: 400, overflowY: "auto", border: "1px solid #ddd", padding: 12 }}>
{messages.map((m, i) => (
<div key={i} style={{ marginBottom: 8 }}>
<strong>{m.role === "user" ? "You" : "Claude"}:</strong> {m.content}
</div>
))}
<div ref={bottomRef} />
</div>
<div style={{ display: "flex", marginTop: 8 }}>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && sendMessage()}
disabled={streaming}
style={{ flex: 1, padding: 8 }}
placeholder="Ask something..."
/>
<button onClick={sendMessage} disabled={streaming}>
{streaming ? "Thinking..." : "Send"}
</button>
</div>
</div>
);
}
This parses the server-sent events manually because fetch doesn't give you SSE parsing out of the box — if you want less boilerplate, EventSource works too, but it only supports GET requests, which is awkward for chat payloads.
Handling errors and rate limits
Production chatbots need to handle three failure cases gracefully:
- Rate limits (429) — show a "please wait" message instead of a blank screen, and consider exponential backoff on retry.
- Network drops mid-stream — wrap the reader loop in a try/catch and mark the message as incomplete rather than leaving it stuck on "Thinking...".
- Long responses hitting max_tokens — check
stop_reasonin the final event and offer a "continue" button that resends the truncated context.
try {
// streaming loop
} catch (err) {
setMessages((prev) => {
const updated = [...prev];
updated[assistantIndex].content += "\n\n_Connection interrupted._";
return updated;
});
} finally {
setStreaming(false);
}
Adding conversation memory and system prompts
Claude's API is stateless — you resend the full message history on every call. For longer conversations, trim older messages or summarize them before sending to stay under context limits. A system prompt (passed as a top-level system field, not inside messages) is the right place to set persona, tone, and constraints for your chatbot.
If you're prototyping this without managing raw Anthropic credentials yourself, /docs/quickstart shows the same request shape against SubToAPI, with the same messages and stream fields — so the React code above doesn't change, only the backend's upstream call does.
Deploying
For production, move the proxy to a serverless function (Vercel, Cloudflare Workers, or a small Express app behind a reverse proxy) and keep the API key in an environment variable, never in client bundle code. If multiple developers or environments need access, API key rotation and scoped keys per environment matter more than most teams initially plan for — worth setting up from day one rather than retrofitting later.
questions
Do I need a backend to use the Claude API in React? Yes. API keys must stay server-side, so a lightweight proxy (Express route, Next.js API route, or serverless function) sits between your React app and Claude.
How do I stream Claude responses into a React component? Use stream: true on the request, read the response body with getReader(), parse the server-sent event chunks, and append content_block_delta text to your message state as it arrives.
Can I use SubToAPI instead of raw Anthropic keys for this tutorial? Yes — swap the backend's fetch URL and headers for https://api.subtoapi.app/v1/messages with a sub_live_... bearer token; the React streaming code stays identical. See /docs/messages for request details or /pricing for plans.