Streaming lets a React Native chat app display the first part of an AI answer while the model generates the rest. It improves time to first visible text when the network and hosting layers pass chunks through as they arrive. Total generation time is a separate metric.
For an Expo app, the architecture is straightforward. The mobile client sends a prompt to an authenticated backend. The backend calls the model and sends text updates over server-sent events (SSE). The app reads the response with expo/fetch. The model API key stays on the server.
1. Define the stream your app will consume
SSE frames are UTF-8 text, and a blank line ends each event. A network chunk can contain part of an event or several events, so the client needs a streaming decoder and an SSE parser. For a chat request that sends a JSON prompt in a POST, use expo/fetch to read the response body incrementally.
A text-only chat needs three application events:
| Event | What the app does |
|---|---|
delta | Appends new text to the active assistant message |
done | Marks the answer complete |
generation-error | Preserves partial text and offers a retry |
A successful response looks like this on the wire:
event: delta
data: {"text":"Server-sent events "}
event: delta
data: {"text":"work over HTTP."}
event: done
data: {}
2. Map model events on the backend
Return Content-Type: text/event-stream; charset=utf-8 and Cache-Control: no-cache, no-transform from the chat endpoint. With OpenAI’s Responses API, relay response.output_text.delta as delta and response.completed as done. Map failures and incomplete responses to generation-error. Once the stream has started, a model error can arrive inside an HTTP 200, so the app should treat a connection that closes without done as interrupted.
Authenticate the user and enforce usage limits before opening the stream. Connect downstream cancellation to the upstream model request so tapping Stop can halt generation as well as close the mobile connection.
3. Read the SSE stream in React Native
Install eventsource-parser in the Expo app. This client helper expects an absolute HTTPS URL for the deployed endpoint and an app session token. TextDecoderStream preserves characters split across network chunks. The parser assembles those decoded chunks into complete events.
import { fetch } from "expo/fetch";
import { createParser } from "eventsource-parser";
export async function streamReply(
url: string,
prompt: string,
sessionToken: string,
signal: AbortSignal,
onDelta: (text: string) => void,
) {
const response = await fetch(url, {
method: "POST",
headers: {
Accept: "text/event-stream",
"Content-Type": "application/json",
Authorization: `Bearer ${sessionToken}`,
},
body: JSON.stringify({ prompt }),
signal,
});
const contentType = response.headers.get("content-type") ?? "";
if (!response.ok || !response.body ||
!contentType.toLowerCase().startsWith("text/event-stream")) {
throw new Error(`Could not open chat stream (${response.status})`);
}
let completed = false;
const parser = createParser({
onEvent({ event, data }) {
if (completed) return;
if (event === "delta") {
const { text } = JSON.parse(data);
if (typeof text !== "string") throw new Error("Invalid text delta");
onDelta(text);
} else if (event === "done") {
completed = true;
} else if (event === "generation-error") {
throw new Error("Generation interrupted");
}
},
});
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
try {
while (!completed) {
const { done, value } = await reader.read();
if (done) break;
parser.feed(value);
}
if (!completed) throw new Error("Connection closed before completion");
} finally {
await reader.cancel().catch(() => {});
reader.releaseLock();
}
}Create one assistant message per request and append deltas to it. Give each generation its own AbortController and wire Stop to abort(). For long replies, batch updates to avoid re-parsing Markdown and recalculating layout for every small fragment.
How five companies approach AI streaming
| Company | Documented practice |
|---|---|
| GeekyAnts | Built Avilo’s React Native voice experience with LiveKit, including session-state synchronization and recovery from interruptions. It illustrates the extra session management required for two-way audio. |
| Vercel | Its Expo guide connects useChat and DefaultChatTransport to expo/fetch for incremental responses from a chat endpoint. |
| OpenAI | Its Responses API sends typed events for text deltas, completion, and failures, giving clients explicit signals for updating the UI. |
| Anthropic | The Claude Messages API streams typed content blocks, pings, and errors over SSE. The app can route visible text and other event types separately. |
| Cloudflare | Workers AI documents returning model output from a Worker with Content-Type: text/event-stream. |
What to test before shipping
- Proxy buffering. Run
curl -Nagainst the deployed endpoint. If deltas arrive in one burst, check whether the reverse proxy buffers the response. NGINX supports disabling buffering for the streaming route. - Backgrounding and reconnects. Use React Native’s
AppStateto detect when the app returns to the foreground. If generation must continue independently, assign it a server-side ID and let the app retrieve the latest saved text. Repeating the originalPOSTcan start another generation. - Partial replies and cancellation. Test a disconnect before
done, a tap on Stop before the first delta, and a character split across byte chunks. Verify that the app keeps any text already displayed.
Measure time to first delta, time to first visible text, and time to completion separately on iOS and Android. If the backend delivers text quickly but the screen still lags, the gap between receipt and render gives the mobile team a concrete place to investigate.





















Add Comment