How to Stream Claude API Responses in React
Streaming Claude API responses in React means reading the response body as a stream of chunks instead of waiting for the full completion, then appending each chunk to component state as it arrives. This gives users the familiar "typing" effect instead of a long blank pause followed by a wall of text. It works with the native fetch API and ReadableStream, no special library required on the frontend.
The short version: your backend (or an API that supports streaming directly) sends a text/event-stream response with stream: true set on the request, your React component reads that stream chunk by chunk with a TextDecoder, parses each Server-Sent Event line, and calls setState to append text as it comes in. Below is a complete, working pattern you can drop into a project today.
Why you can't just await response.json()
A normal API call waits for the entire response, parses it as JSON, and resolves. Streaming responses never send one JSON blob — they send a sequence of events over an open connection, usually formatted as Server-Sent Events (SSE), where each line looks like:
event: content_block_delta
data: {"type":"content_block_delta","delta":{"text":"Hello"}}
To consume this in the browser you need the raw ReadableStream from response.body, not the parsed JSON helper methods.
Step 1: Set up the fetch call with streaming enabled
Whether you're calling Claude directly or through a proxy like SubToAPI, the request itself looks like a normal POST — streaming is controlled by a stream: true flag in the body and by reading the response differently on the client.
async function streamCompletion(prompt, onChunk) {
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${process.env.NEXT_PUBLIC_SUBTOAPI_KEY}`,
},
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 1024,
stream: true,
messages: [{ role: "user", content: prompt }],
}),
});
const reader = response.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(); // keep incomplete line for next chunk
for (const line of lines) {
if (!line.startsWith("data: ")) continue;
const payload = line.slice(6);
if (payload === "[DONE]") return;
try {
const parsed = JSON.parse(payload);
const text = parsed.delta?.text;
if (text) onChunk(text);
} catch {
// partial JSON, ignore and wait for more data
}
}
}
}
Never put a real API key in client-side code shipped to end users. The example above assumes a protected internal tool or a server-side environment variable injected at build time for a controlled demo. For production apps, route the request through your own backend or an edge function that holds the secret — see the pattern below.
Step 2: Wire it into a React component
import { useState, useCallback } from "react";
export default function ChatStream() {
const [output, setOutput] = useState("");
const [loading, setLoading] = useState(false);
const handleSubmit = useCallback(async (prompt) => {
setOutput("");
setLoading(true);
await streamCompletion(prompt, (chunk) => {
setOutput((prev) => prev + chunk);
});
setLoading(false);
}, []);
return (
<div>
<button onClick={() => handleSubmit("Explain event loops in one paragraph")}>
Ask Claude
</button>
<p>{output}</p>
{loading && <span>streaming...</span>}
</div>
);
}
The key detail is using the functional form of setState ((prev) => prev + chunk) rather than closing over a stale output variable. Since chunks arrive in rapid succession, React can batch updates, and relying on a captured value from the outer scope will drop characters.
Step 3: Route it through a backend for safety
In a real product, the browser should never hold your API key. A minimal Next.js API route or any Node server works as a pass-through:
// app/api/stream/route.js
export async function POST(req) {
const { prompt } = await req.json();
const upstream = 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-sonnet-4",
max_tokens: 1024,
stream: true,
messages: [{ role: "user", content: prompt }],
}),
});
return new Response(upstream.body, {
headers: { "Content-Type": "text/event-stream" },
});
}
Your React component then calls /api/stream instead of the external API directly, and the fetch/reader logic on the client stays exactly the same. This is the safest pattern: the secret key lives only in your server's environment variables, never in the bundle shipped to browsers.
Common pitfalls
- Buffering the whole response in a proxy or CDN. Some edge configurations buffer bodies before forwarding them, which defeats streaming entirely. Test with
curl -Nagainst your own endpoint to confirm chunks arrive incrementally. - Forgetting the trailing partial line. SSE chunks don't always align with line boundaries — always hold back the last (possibly incomplete) line in a buffer, as shown above.
- Re-rendering too aggressively. Appending every single token to state can cause excessive re-renders on long responses. Batching updates every 2–3 chunks with a small debounce improves perceived smoothness without noticeable lag.
- Not handling abort. Use an
AbortControllertied to a cleanup function if the component unmounts mid-stream, otherwise you'll get console warnings and wasted tokens.
If you want streaming, tool use, and usage metadata without building and maintaining your own proxy layer, SubToAPI exposes Claude through a standard streaming-capable endpoint with per-key usage tracking. The quickstart covers authentication, and the streaming docs go deeper into SSE event types and tool-call deltas if your chat UI also needs to render tool invocations inline.
Questions
Does streaming reduce total response time? No — total generation time is roughly the same. Streaming improves perceived latency by showing text as it's generated instead of after the full response completes.
Can I use EventSource instead of fetch for this? Not directly for POST requests with a JSON body — EventSource only supports GET. Stick with fetch and ReadableStream for Claude-style streaming APIs that require a POST body.
What happens if the connection drops mid-stream? You'll get a partial response with no automatic resume. Track how much text has already been appended and, if needed, implement a retry that re-sends the prompt with the partial output as context.