How Token Streaming Works Between FastAPI and React
To stream LLM tokens from a Python FastAPI backend to a React frontend, FastAPI sends chunks over an open HTTP response using StreamingResponse, and React reads those bytes progressively with fetch() and response.body.getReader() (which returns a ReadableStreamDefaultReader over the ReadableStream).
- No polling needed: Tokens appear in the UI as soon as the model generates them instead of waiting for the full reply.
- Works with
POSTrequests: UnlikeEventSource,fetch()+ReadableStreamlets you send a JSON body (such as chat history and prompt settings) and custom headers easily. - Chunk boundaries vary: A single read from the stream can return part of a word, multiple tokens, or a split multi-byte character, so decoding with
{ stream: true }is important.
Step-by-Step Flow
- FastAPI yields text chunks: An async generator yields string chunks from the LLM stream and returns a
StreamingResponsewithmedia_type="text/plain; charset=utf-8". - React posts the prompt: A
POSTrequest sends the user message and passes anAbortControllersignal so the user can cancel mid-stream. - React reads the
ReadableStream: Loop overreader.read(), decode bytes usingTextDecoderwith{ stream: true }, and append new text to React state. - Clean up on finish or cancel: Handle
done === true,AbortError, and HTTP errors cleanly.
FastAPI Backend Example (Python)
from typing import AsyncIterator
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI
from pydantic import BaseModel
app = FastAPI()
client = AsyncOpenAI()
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class ChatRequest(BaseModel):
prompt: str
async def token_generator(prompt: str) -> AsyncIterator[str]:
stream = await client.responses.create(
model="gpt-4o-mini",
input=prompt,
stream=True,
)
async for event in stream:
if event.type == "response.output_text.delta":
yield event.delta
@app.post("/api/chat/stream")
async def stream_chat(req: ChatRequest) -> StreamingResponse:
return StreamingResponse(
token_generator(req.prompt),
media_type="text/plain; charset=utf-8",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
},
)
React Frontend Example (ReadableStream)
import { useRef, useState } from "react";
export function StreamingChat() {
const [prompt, setPrompt] = useState("");
const [output, setOutput] = useState("");
const [isStreaming, setIsStreaming] = useState(false);
const [error, setError] = useState("");
const abortRef = useRef(null);
async function handleSubmit(e) {
e.preventDefault();
if (!prompt.trim() || isStreaming) return;
setOutput("");
setError("");
setIsStreaming(true);
const controller = new AbortController();
abortRef.current = controller;
try {
const response = await fetch("http://localhost:8000/api/chat/stream", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt }),
signal: controller.signal,
});
if (!response.ok || !response.body) {
throw new Error(`HTTP \${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { value, done } = await reader.read();
if (done) break;
const chunkText = decoder.decode(value, { stream: true });
setOutput((prev) => prev + chunkText);
}
// Flush any remaining buffered multi-byte character
const tail = decoder.decode();
if (tail) {
setOutput((prev) => prev + tail);
}
} catch (err) {
if (err.name !== "AbortError") {
setError(err.message || "Streaming failed");
}
} finally {
setIsStreaming(false);
abortRef.current = null;
}
}
function handleStop() {
abortRef.current?.abort();
}
return (
<div>
<form onSubmit={handleSubmit}>
<input
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
placeholder="Ask something..."
/>
<button type="submit" disabled={isStreaming}>
Send
</button>
{isStreaming && (
<button type="button" onClick={handleStop}>
Stop
</button>
)}
</form>
{error && <p>{error}</p>}
<pre>{output}</pre>
</div>
);
}
Helpful Tips for Production
- Disable proxy buffering: Adding
X-Accel-Buffering: noandCache-Control: no-cachehelps prevent reverse proxies like Nginx from holding chunks before flushing. - Batch UI updates if needed: Very fast token streams can trigger frequent re-renders; accumulating chunks in a ref or
requestAnimationFramekeeps large responses smooth. - Use structured SSE events for metadata: Plain text is simple for raw tokens, while SSE-formatted lines (
data: \n\n) work well if you also need to stream citations, tool status, or error events.
You must log in or register to comment.
