Claude API React Frontend Chat Widget: Build Guide
Building a Claude API chat widget in React
If you're searching for "claude api react frontend chat widget," you're probably trying to drop a conversational UI into a product — a support widget, an in-app assistant, a docs search box — and you want it to feel like ChatGPT: streaming text, markdown rendering, a clean input box, and no page reloads. This is very doable with plain React, a handful of hooks, and a backend endpoint that talks to Claude.
The short answer: you build a <ChatWidget /> component that manages message state, sends requests to a server-side route (never directly to Anthropic or any provider from the browser), and renders the streamed response token by token using the Fetch API's ReadableStream. Below is a complete, working pattern you can adapt.
Why you can't call Claude directly from the browser
The first mistake developers make is importing an SDK and calling the API straight from a React component. Don't do this — it means shipping your secret key inside the JavaScript bundle, where anyone can open DevTools and steal it. API providers, including Claude and gateways like SubToAPI, expect the request to come from a server that holds the key.
The correct architecture is:
- React widget collects user input and renders messages.
- A lightweight backend route (Node, Next.js API route, Express, whatever you already run) receives the message history and forwards it to the Claude API (or a gateway like SubToAPI).
- The backend streams the response back to the browser as it arrives.
This keeps your key server-side and lets you add rate limiting, logging, or auth checks in one place.
The backend proxy route
A minimal Express route that proxies to SubToAPI (which issues sub_live_... keys and exposes a Claude-compatible /v1/messages endpoint with streaming) looks like this:
// server/chat.js
import express from "express";
const router = express.Router();
router.post("/api/chat", async (req, res) => {
const { messages } = req.body;
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",
max_tokens: 1024,
stream: true,
messages,
}),
});
res.setHeader("Content-Type", "text/event-stream");
upstream.body.pipe(res);
});
export default router;
Full request/response shapes are documented at /docs/messages, and streaming event details at /docs/streaming.
The React widget component
On the frontend, read the stream and append tokens to the last assistant message as they arrive:
import { useState, useRef } from "react";
export default function ChatWidget() {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState("");
const scrollRef = useRef(null);
async function sendMessage() {
const next = [...messages, { role: "user", content: input }];
setMessages([...next, { role: "assistant", content: "" }]);
setInput("");
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages: next }),
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
let assistantText = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
for (const line of chunk.split("\n")) {
if (!line.startsWith("data:")) continue;
const data = line.replace("data:", "").trim();
if (data === "[DONE]") continue;
const parsed = JSON.parse(data);
if (parsed.delta?.text) {
assistantText += parsed.delta.text;
setMessages((prev) => {
const updated = [...prev];
updated[updated.length - 1] = {
role: "assistant",
content: assistantText,
};
return updated;
});
}
}
}
}
return (
<div className="chat-widget">
<div className="messages" ref={scrollRef}>
{messages.map((m, i) => (
<div key={i} className={`msg ${m.role}`}>
{m.content}
</div>
))}
</div>
<div className="input-row">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && sendMessage()}
placeholder="Ask something..."
/>
<button onClick={sendMessage}>Send</button>
</div>
</div>
);
}
This is intentionally minimal — no state management library, no third-party chat UI kit. For a production widget, add:
- Markdown rendering with
react-markdownso code blocks and lists format correctly. - Auto-scroll on new content using a
useEffectwatchingmessages. - A typing indicator while
assistantTextis empty but the request is in flight. - Error handling for network drops mid-stream — buffer partial text and show a retry button.
- Message history limits so you don't send an unbounded context window on every request.
Handling tool calls in the widget
If your assistant needs to call functions (look up an order, search a database), the stream will include tool-use blocks before the final text. Your backend proxy should detect these, execute the tool, and send a follow-up request with the result before resuming the stream to the browser. The request/response shape for this is covered at /docs/tools — the widget component itself doesn't change, it just waits a bit longer for the final text chunks.
Where SubToAPI fits
If you don't want to manage separate Claude credentials, rate limits, and usage tracking per app, SubToAPI gives you a single sub_live_... key, streaming support, and per-key usage metadata you can show to customers or bill against. The proxy route above works unmodified against it — swap in your key from /signup and follow /docs/quickstart to get the first response back in minutes. Plans start at €9/month on the Solo tier, with team seats on the Team and Scale plans — see /pricing.
questions
Can I call the Claude API directly from React without a backend? Technically yes with a CORS-permissive proxy, but you'd expose your API key in the browser bundle. Always route requests through a server you control, even if it's a single serverless function.
How do I show streaming text instead of waiting for the full reply? Use stream: true in the request and read the response body with ReadableStream/getReader() on the frontend, appending each delta.text chunk to the current message as shown above.
Does this pattern work with Next.js instead of Express? Yes — replace the Express route with a Next.js Route Handler (app/api/chat/route.ts) that does the same fetch-and-pipe logic; the React widget code is unchanged either way.