Free tools Windows power users keep installed
One-click scans. No signup required.
To stream server-sent events (SSE) from FastAPI to a React 19 app, return FastAPI’s EventSourceResponse, yield properly framed events, and consume them with the browser’s EventSource API or a Fetch stream. Preventing buffering also depends on the proxy and hosting layers between your app and browser; an endpoint yielding events does not guarantee they arrive promptly.
How does SSE work between FastAPI and React?
SSE is a one-way HTTP text stream from server to browser. The response uses the text/event-stream content type. Each event is a group of fields—such as data, event, id, or retry—followed by a blank line. The blank line ends the event; network chunks are not guaranteed to line up with event boundaries.
As an Amazon Associate I earn from qualifying purchases.
This is application data streaming, not React server rendering that streams HTML. React 19 does not provide or replace SSE transport: browser APIs receive the stream, and your component updates its UI from events. See FastAPI’s SSE tutorial, MDN’s EventSource guide, and the React 19 release notes.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
How do I stream SSE from FastAPI to React?
1. Define the event contract
Choose event names and a small, serializable payload shape before connecting the client. Add stable event IDs if clients need to resume after reconnecting. For a finite stream, define how completion is represented—for example, a named completion event or a terminal status in the payload.
#1 Best Overall
FastAPI’s ServerSentEvent supports metadata such as event, id, retry, and comment. Its data field is JSON-encoded; use raw_data when the event data must remain preformatted text. The FastAPI SSE reference describes these fields.
2. Emit events from FastAPI
Native SSE support was added in FastAPI 0.135.0, according to its tutorial. Check your project’s pinned FastAPI version before using this API; older installations may require a different response implementation.
from collections.abc import AsyncIterable
from fastapi import FastAPI
from fastapi.sse import EventSourceResponse, ServerSentEvent
app = FastAPI()
@app.get("/events", response_class=EventSourceResponse)
async def events() -> AsyncIterable[ServerSentEvent]:
yield ServerSentEvent(data={"status": "started"}, event="status", id="1")
yield ServerSentEvent(data={"progress": 50}, event="progress", id="2")
For ordinary JSON payloads, FastAPI also documents yielding typed model instances for serialization as event data. Use an async generator when it awaits I/O or produces asynchronous events. Avoid blocking the event loop with synchronous work; FastAPI documents that synchronous generator endpoints are run appropriately.
Rank #2
Complete authorization and input validation before returning the streaming response. In HTTP streaming generally, response status and headers are committed when streaming starts, so an error discovered afterward cannot be handled like an ordinary pre-response validation failure.
3. Subscribe from a React component
For a conventional GET event feed, native EventSource handles SSE framing and dispatches named events. Open the connection in an effect, update state from the event payload, and close the connection during cleanup.
import { useEffect, useState } from "react";
export function LiveStatus() {
const [events, setEvents] = useState([]);
useEffect(() => {
const source = new EventSource("/events");
source.addEventListener("progress", (event) => {
setEvents((current) => [...current, JSON.parse(event.data)]);
});
source.onerror = () => {
// Show a reconnecting or failed state as appropriate.
};
return () => source.close();
}, []);
return <pre>{JSON.stringify(events, null, 2)}</pre>;
}
This example listens for the named progress event. Add listeners for any other event names your server emits, and make sure the component’s error and completion states match your event contract.
Should I use EventSource or fetch for SSE?
| Consideration | Native EventSource | Fetch with a readable body |
|---|---|---|
| Parsing | The browser parses SSE and dispatches named events. | Your application must parse SSE framing and fields. |
| Request shape | A URL-based event-stream connection. | Supports custom methods, headers, request bodies, and cancellation. |
| Reconnect behavior | Provides native event-stream reconnection behavior. | You implement retry and resume policy. |
| Good fit | Simple one-way GET feeds. | POST streams or requests that need custom headers or lifecycle control. |
| Main caution | Plan authentication, CORS, and connection lifecycle around its interface. | Decode and parse across arbitrary chunk boundaries; do not wait for the whole response. |
Prefer EventSource unless the request needs Fetch capabilities it does not offer. For Fetch, the browser exposes a readable response body, but React does not parse the SSE protocol for you. MDN documents both EventSource and incremental Fetch response reading.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Read Fetch responses incrementally
Check the HTTP response before reading its body. Decode UTF-8 incrementally, retain incomplete text between reads, and dispatch an event only when its blank-line delimiter is complete. A production parser must account for LF and CRLF line endings, multiple data: lines, comments, named events, IDs, retry fields, and a final unterminated buffer.
const controller = new AbortController();
const response = await fetch("/events", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ topic: "build" }),
signal: controller.signal,
});
if (!response.ok || !response.body) {
throw new Error("Stream request failed");
}
const reader = response.body
.pipeThrough(new TextDecoderStream())
.getReader();
let buffer = "";
while (true) {
const { value = "", done } = await reader.read();
buffer += value;
// Parse complete SSE records separated by a blank line.
// Preserve any incomplete suffix in buffer for the next read.
if (done) break;
}
Put the Fetch operation in a React effect or another lifecycle-managed function, and abort the controller during cleanup or when the user cancels. Define how the UI handles errors, retries, duplicate events, stale requests, and completion; a custom Fetch reader does not automatically inherit EventSource’s reconnection behavior.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.How do I stop FastAPI SSE from buffering?
FastAPI’s SSE response documents a keep-alive comment ping every 15 seconds when there are no messages, along with Cache-Control: no-cache and X-Accel-Buffering: no defaults. These settings help with common proxy behavior, but they cannot guarantee that every intermediary forwards data immediately.
Check the full delivery path
- Inspect the reverse proxy, ingress, CDN, load balancer, compression middleware, and hosting platform between the ASGI app and browser.
- Verify that each layer supports streaming and is not accumulating response bytes before forwarding them.
- Test with events emitted at known intervals and compare when they are produced with when the browser receives them.
- Log production and receipt timestamps to distinguish server-side delay from intermediary buffering.
React may also batch state updates even when chunks reach the browser promptly. That is different from a proxy withholding bytes. Test the deployed path; a local endpoint that yields events is not proof of end-to-end unbuffered delivery.
Recommended Free Tools
How do reconnects and event resumption work?
When an EventSource connection reconnects, the browser can send Last-Event-ID if events had IDs. That header identifies a position; it does not preserve the events. To resume reliably, the server needs logic that maps the ID to retained or replayable data, as described in the FastAPI SSE tutorial.
Decide whether your application needs replay, how long event history is retained, and how the client handles duplicates or an ID that is no longer available. For streams that do not need resume, keep the event contract and UI error state simple rather than implying that reconnecting restores missed data.
What to verify before shipping
- The deployed FastAPI version supports the SSE API used by the endpoint.
- The response is served as
text/event-stream, and event fields end with the required blank line. - The browser receives events incrementally through the actual proxy and hosting chain.
- EventSource connections close on component cleanup, or Fetch readers are aborted.
- Authentication, CORS, errors, completion, and any replay policy are defined for the selected client.
For the relevant React streaming APIs and rendering distinctions, see the official React 19.3 release notes.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




