Every AI chat demo looks great on a laptop. Then you put it on a phone and the problems start: there is no EventSource in React Native, a network chunk can split a JSON payload in half, the model's markdown arrives as raw text with nowhere to render it, the conversation quietly grows past the context window, and the subscription you added to pay for the tokens can be bypassed by anyone with a rooted device.
I built Expo AI App Kit, a React Native starter for exactly this shape of app — streaming chat, markdown answers, saved history, a RevenueCat paywall and a server proxy — and this post is the architecture behind it: the four problems above, the code that solves them, and the trade-offs I would keep (or not) on the next app.
Stack for reference: Expo SDK 58, React Native 0.88, React 19, TypeScript 6 in strict mode, no UI library, no state library, no markdown library.
The rule that made everything else testable
One rule shaped the whole codebase: src/core never imports React Native.
Parsing, token budgeting, plan rules, the chat reducer and storage repositories are plain TypeScript. React Native appears only in the screens, the components and two storage adapters. That means all of it can run under Node, which is why the kit's test suite is 9 files / 204 tests that finish in under three seconds, and why npm run demo can drive the same code the phone runs through a full conversation, a paywall block and a simulated purchase.
If you take one thing from this post: keep the streaming parser and the prompt builder out of your components. They are where the bugs live, and you want them covered by tests, not by tapping around a simulator.
Problem 1: SSE without EventSource
React Native has fetch, but no EventSource. Even if it did, you would not want it: it cannot send a POST body, cannot set your own headers, and gives you no way to abort a request cleanly. So you read the body yourself:
const response = await fetch(`${base}/api/chat`, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'text/event-stream' }, body: JSON.stringify({ messages, model, max_output_tokens: maxOutputTokens }), signal: controller.signal, }); const reader = response.body!.getReader(); const decoder = new TextDecoder(); const accumulator = new StreamAccumulator('openai'); while (true) { const { done, value } = await reader.read(); if (done) break; const result = accumulator.feed(decoder.decode(value, { stream: true })); if (result.text) onDelta(result.text); if (result.error) throw result.error; if (result.done) return; } Two details in those eight lines are easy to miss.
decoder.decode(value, { stream: true }) is not optional. A UTF-8 character can straddle two network chunks. Without the streaming flag the decoder treats each chunk as a complete document, and a Korean, Japanese or emoji character split at the boundary turns into ``. Latin-only testing will never show you this bug.
Chunk boundaries have nothing to do with event boundaries. A chunk can contain half an event, three events, or one and a half. So the parser buffers text and only emits on the blank line that terminates an SSE frame:
`ts
export class SSEParser {
private buffer = '';
private pendingCR = false;
push(chunk: string): StreamEvent[] {
let text = chunk;
// A trailing \r may be the first half of a \r\n split across chunks.
if (this.pendingCR) {
text = \r${text};
this.pendingCR = false;
}
if (text.endsWith('\r')) {
this.pendingCR = true;
text = text.slice(0, -1);
}
this.buffer += text.replace(/\r\n?/g, '\n'); const events: StreamEvent[] = []; let index = this.buffer.indexOf('\n\n'); while (index !== -1) { const block = this.buffer.slice(0, index); this.buffer = this.buffer.slice(index + 2); const parsed = parseBlock(block); if (parsed) events.push(parsed); index = this.buffer.indexOf('\n\n'); } return events; }
flush(): StreamEvent[] { /* emit a final block that never got its blank line */ }
}
`
The held-back \r is the part people skip. If a chunk ends with \r and the next begins with \n, naively normalising each chunk separately produces \n\n where you wanted \r\n, and you get a phantom event boundary in the middle of a JSON payload. The parser holds the \r until it knows what follows, then normalises everything to \n.
The same parser is unit-tested against the cases that actually happen: a boundary in the middle of data: {"choices":[{"delta":{"con, several events arriving in one chunk, \r\n and bare \r line endings, multi-line data: fields, keep-alive comments (: ping), and a stream that ends without a final blank line (flush()).
One parser, three dialects
Providers disagree about the envelope, not the transport. So parsing is split in two: the SSEParser produces { event, data, id } frames, and interpretEvent maps a frame to text | done | error | ignore for a chosen dialect.
| Dialect | Text | End | Notes |
|---|---|---|---|
openai | choices[0].delta.content (string or content-parts array) | finish_reason, [DONE] | Does not use the event: field |
anthropic | content_block_delta.delta.text | message_stop | Named events |
plain | the whole data: payload | [DONE] | For proxies that stream raw text |
This is why the client works against your own proxy, a direct OpenAI call, or an Anthropic-compatible endpoint without three copies of the streaming loop.
A malformed frame should not kill the chat. If a data: line is not valid JSON, interpretEvent returns a retryable error instead of throwing. One bad frame becomes a message the user can retry, not an unhandled promise rejection. Upstream errors ({"error": {...}}) are read for their message and surfaced the same way.
Cancelling, and knowing what you cancelled
The client wraps the request in an AbortController and also sets a timeout that aborts the same controller. That creates an ambiguity: both a user pressing Stop and a timeout surface as AbortError. If you treat them the same, a timeout looks like a user action and loses the retry affordance.
The kit distinguishes them by checking the caller's signal: if the user's signal is aborted, the stream is done (and the partial answer is kept, marked stopped); otherwise an AbortError becomes an AppError('timeout'). Small thing, but it is the difference between "Stopped" and "Taking too long — retry?" on screen.
Problem 2: streaming state that does not corrupt itself
The classic React streaming bug is a stale closure appending a delta to the wrong message, or two messages receiving the same delta after a fast re-render. The fix is not useRef everywhere; it is to make state transitions pure.
The kit's chat state is a reducer with four transition types that matter:
`ts
case 'delta': {
const messages = state.messages.map((message) =>
message.id === action.id
? { ...message, content: message.content + action.text, status: 'streaming' as const }
: message,
);
return { ...state, messages, streamingId: action.id };
}
case 'complete':
return { messages: mapStatus(state.messages, action.id, 'complete'), streamingId: null, error: null };
case 'fail':
return { messages: mapStatus(state.messages, action.id, 'error', action.error.userMessage),
streamingId: null, error: action.error };
case 'stop':
return { messages: mapStatus(state.messages, action.id, 'stopped', undefined, true),
streamingId: null, error: null };
`
The assistant placeholder is appended before the first token arrives, with status: 'streaming'. That single decision gives you the typing caret for free, keeps the list height stable, and makes "which message is live" a field on the message rather than a second piece of state that can drift.
status is the whole state machine: streaming → complete | stopped | error. Nothing in the UI infers state from content length — an empty completed answer and a stalled stream look different on purpose.
Two details worth copying:
- Count the message before the network call. The daily usage counter increments when
send()is called, not when the stream finishes. A crash mid-stream must not refund a message, or airplane-mode toggling becomes a free-tier exploit. - Retry costs a message, and says so.
retry()runs the samecheckSendas a new message. A silent retry loop is a way to burn a user's quota without them noticing.
The hook (useChat) owns effects, the abort controller and persistence; the reducer owns state. That split is why every transition above is a six-line unit test instead of a manual QA checklist.
Problem 3: markdown with no DOM
Model output is markdown, and React Native has no HTML renderer. The usual options are a WebView (an entire browser per bubble, non-selectable text by default, scroll and height fights, and a new place for untrusted content to run) or a large JS markdown library that produces HTML you then have to parse back into something renderable.
I took a third option: parse a practical GFM subset into a typed AST and render the AST with Text and View.
`ts
export type Block =
| { type: 'heading'; level: 1 | 2 | 3 | 4 | 5 | 6; inlines: Inline[] }
| { type: 'paragraph'; inlines: Inline[] }
| { type: 'code'; language: string | null; code: string }
| { type: 'list'; ordered: boolean; start: number; items: Inline[][] }
| { type: 'quote'; blocks: Block[] }
| { type: 'divider' }
| { type: 'table'; align: Align[]; header: Inline[][]; rows: Inline[][][] };
export type Inline =
| { type: 'text'; text: string }
| { type: 'strong'; children: Inline[] }
| { type: 'em'; children: Inline[] }
| { type: 'del'; children: Inline[] }
| { type: 'code'; text: string }
| { type: 'link'; href: string; children: Inline[] };
`
That covers what assistants actually emit: headings, paragraphs, fenced code with a language label, bullet and ordered lists, blockquotes, dividers, tables, and inline code/bold/italic/strike/links. Rendering is ordinary RN:
`tsx
case 'code':
return (
<View style={{ backgroundColor: colors.codeBg, borderRadius: 12, overflow: 'hidden' }}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', paddingHorizontal: 12 }}>
<Text style={{ color: '#9A9AAE', fontSize: 11, fontFamily: MONO }}>
{(block.language ?? 'text').toUpperCase()}
</Text>
<Text style={{ color: '#6E6E86', fontSize: 11, fontFamily: MONO }}>code</Text>
</View>
<ScrollView horizontal showsHorizontalScrollIndicator={false}>
<Text selectable style={{ color: '#E8E8F2', fontSize: font.mono, fontFamily: MONO }}>
{block.code}
</Text>
</ScrollView>
</View>
);
`
What you get that a WebView does not give you: every answer is selectable and copyable with the platform's own selection handles; the theme is the app theme (light/dark/system) with no injected CSS; long code blocks scroll horizontally inside a fixed-width card instead of stretching the bubble; tables scroll the same way; links go through Linking.openURL, so you decide what happens when one is tapped.
What you give up is real, and I would rather write it down than let it surprise a buyer: no raw HTML, no images in answers, no footnotes, no nested lists, no setext headings, no reference links. Each one costs layout or security surface, and none of them appears often enough in model output to justify it. The parser is also deliberately shallow — a list item's continuation lines are joined, not nested.
The parsing cost during streaming
MarkdownView parses the whole message string on every render, memoised per message with useMemo. During streaming that string changes on every delta, so in the worst case you re-parse the entire answer a few dozen times a second. For typical answers (a few hundred to a couple of thousand characters) that is fine on a mid-range phone, and it is what the kit ships.
If you stream very long answers, the next step is to parse only the tail: keep a cache of blocks that are "sealed" (everything before the last blank line outside an open code fence) and re-parse from the last fence boundary. I did not build that, because it adds a class of subtle bugs — a table header whose separator row has not arrived yet — for a cost most chats never hit. Know the ceiling, keep the simple version.
One parser bug worth mentioning because everyone hits it: a fenced code block is only closed by a fence of the same marker. If your regex accepts as closing a ~~~` block, an answer that shows markdown inside a code sample will swallow the rest of the message.
Problem 4: the conversation will outgrow the context window
Every AI app that forgets token budgeting eventually gets a 400 from the provider mid-demo, usually with a long conversation the user cares about. Two things need to happen: estimate the size before sending, and decide what to drop.
The kit estimates cheaply and deliberately pessimistically:
export function estimateTokens(text: string): number { let cjk = 0; for (const char of text) { const code = char.codePointAt(0) ?? 0; if ((code >= 0x3000 && code <= 0x9fff) || (code >= 0xac00 && code <= 0xd7af) || (code >= 0xf900 && code <= 0xfaff)) cjk += 1; } const latin = text.length - cjk; return Math.ceil(latin / 4) + cjk; } Roughly four Latin characters per token, one per CJK character. It over-estimates slightly on English and is close enough on Korean and Japanese. This is not billing — it is a guardrail, and going under the window is the only mistake that costs money.
The builder then spends the budget from the newest turn backwards:
// Reserve the system prompt first. let budget = maxInputTokens - (systemText ? estimateTokens(systemText) + overhead : 0); for (let i = capped.length - 1; i >= 0; i -= 1) { const message = capped[i]; const cost = estimateTokens(message.content) + overhead; // overhead ≈ 4 per message if (kept.length === 0) { // The newest turn is never dropped — only shortened. if (cost > budget) { kept.push({ role: message.role, content: truncateToTokens(message.content, budget - overhead) }); truncated = true; } else { kept.push({ role: message.role, content: message.content }); } budget -= cost; continue; } if (cost > budget) { dropped += 1; continue; } kept.push({ role: message.role, content: message.content }); budget -= cost; } Four decisions in there are worth copying:
- Walk backwards, not forwards. The most recent turns are the ones the answer depends on. Truncating from the front keeps the question that was just asked.
- Never drop the newest user turn. If it alone exceeds the budget, shorten it, append
…, and returntruncated: trueso the UI can tell the user instead of silently answering a different question. - Reserve the system prompt before spending on turns. Otherwise a long system prompt plus a long history is over budget before you notice.
- Merge consecutive same-role turns. Most providers reject
user, user. Dropping a turn from the middle can produce exactly that, so the builder merges neighbours with a blank line between.
buildPrompt returns { messages, dropped, estimatedTokens, truncated }. dropped is what the UI needs to say "using the last N messages" honestly; truncated is what it needs to say the current message was shortened.
The default is 6,000 input tokens and 20 turns, which sits comfortably inside an 8k-context model. If you switch to a 128k model, raise the budget — but do not delete the guard. A user will paste a 200-page document into the composer within a week.
The key cannot live in the app
An .ipa or .apk can be unpacked. Any API key shipped in the bundle is a public key with your billing attached. So the app talks only to a proxy you run, and the proxy holds the key.
The proxy in the kit is written against the Web Request/Response standard with no framework, so the same handler runs on Vercel Edge, Cloudflare Workers, Deno Deploy, Bun, and a plain Node server (there is a ~40-line wrapper for the last one, npm run proxy).
Its responsibilities, in order:
Validate before you spend money. The endpoint is public the moment it is deployed, so every field is hostile:
const MAX_MESSAGES = 40; const MAX_MESSAGE_CHARS = 20_000; const MAX_TOTAL_CHARS = 60_000; // roles allowlisted, every string bounded, total bounded, // the last message must be from the user, // the model must be in AI_ALLOWED_MODELS, // max_output_tokens clamped to [16, AI_MAX_OUTPUT_TOKENS], // temperature clamped to [0, 2]. The model allowlist matters more than it looks. Without it, a caller can name the most expensive model on your account and stream it at your expense. Same for max_output_tokens: a client that asks for 100k output tokens should get your cap, not its wish.
Rate limit per caller. A fixed-window limiter, in memory:
export class FixedWindowLimiter { private readonly hits = new Map<string, { count: number; resetAt: number }>(); constructor(private readonly limitPerWindow: number, private readonly windowMs = 60_000) {} take(key: string, now = Date.now()): RateDecision { const entry = this.hits.get(key); if (!entry || entry.resetAt <= now) { this.hits.set(key, { count: 1, resetAt: now + this.windowMs }); return { allowed: true, remaining: this.limitPerWindow - 1, retryAfterMs: 0 }; } if (entry.count >= this.limitPerWindow) { return { allowed: false, remaining: 0, retryAfterMs: entry.resetAt - now }; } entry.count += 1; return { allowed: true, remaining: this.limitPerWindow - entry.count, retryAfterMs: 0 }; } } Default 30 requests per minute per IP. Be honest about what this is: on serverless it counts per warm instance, and the key is an IP, which a mobile carrier NAT shares among thousands of people. It stops one phone in a loop. It is not a quota. For a real quota, put the counter in Redis or KV, key it by your user id, and enforce the plan limit there — not in the app.
Stream through without buffering. The response is passed straight through with the headers that stop intermediaries from holding it:
return new Response(response.body, { status: 200, headers: { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-store, no-transform', 'x-accel-buffering': 'no', // nginx / Vercel: do not buffer the stream connection: 'keep-alive', }, }); If you have ever seen an AI app that delivers the whole answer at once after a long pause, it was almost always a proxy or load balancer buffering the stream. no-transform and x-accel-buffering: no are the two lines that fix it most often.
Never forward an upstream error body. Provider errors can echo request details, and some include key fragments. The proxy logs the detail server-side and returns a short, safe message with 502 or 429, plus retry-after when it is the provider rate-limiting you.
Propagate the abort. When the phone hangs up, the handler aborts the upstream request too, and returns 499. Otherwise every stopped message keeps billing tokens on the server after the user has moved on.
RevenueCat, and the paywall bug that costs real money
The entitlement layer is an interface with two implementations: a demo provider that writes to device storage (so the paywall flow works with no store account, in Expo Go) and a RevenueCat adapter. The RevenueCat SDK is a native module, so it is loaded lazily and typed structurally — the app builds and runs in Expo Go without it, and Settings shows "not installed" instead of crashing on import.
The part I would test hardest is the mapping from CustomerInfo to your plan, because getting it wrong is how apps keep charging people who cancelled:
export function entitlementFromCustomerInfo(info: CustomerInfoLike, entitlementId = 'pro'): Entitlement { const active = info.entitlements?.active ?? {}; const match = active[entitlementId] ?? Object.values(active).find((item) => item.identifier === entitlementId) ?? Object.values(active)[0]; if (!match) return FREE; const product = (match.productIdentifier ?? '').toLowerCase(); const plan: PlanId = product.includes('life') ? 'lifetime' : 'pro'; const expiresAt = match.expirationDate ?? undefined; return { plan, source: 'revenuecat', active: true, ...(expiresAt ? { expiresAt } : {}) }; } Three traps in twenty lines:
-
activeis not "paid". It is "the entitlement has not expired yet". Always carryexpirationDateand check it against the device clock at read time; a cachedisProboolean will be wrong for a day after a cancellation. - A lifetime purchase has no expiry. You cannot tell it apart from a broken subscription by dates alone, so the plan is recognised by the product identifier (
...life...). Rename your lifetime product so it containslife, or add an explicit map. -
restorePurchasesis an App Store review requirement. Not an edge case — a reviewer will look for the button, and users who reinstall need it.
Then the rule that matters most: the client's plan rules only shape the UI. FREE_LIMITS and PRO_LIMITS drive the counter, the block reason and the paywall copy; they are trivially bypassable on a rooted device. The limit that actually protects your bill is the one in the proxy, keyed by user, enforced server-side. Every AI app that leaks money has a paywall that exists only in the app.
What I'd carry to the next app
A few smaller decisions that earned their place:
- A demo mode that is on by default.
EXPO_PUBLIC_DEMO_MODE=truemakes the app stream fixture answers with realistic delays, so a fresh clone runs in Expo Go with no key, and screenshots and store review do not depend on a provider being up. The CLI demo in this repo runs the same core through a full conversation, a paywall block and a purchased upgrade — 10 checks, all green. - One JSON blob per concern in AsyncStorage, read defensively. Corrupt JSON returns an empty list instead of throwing, and wrongly shaped rows are filtered out. Caps (conversations, messages per conversation, history days) apply on write and in
prune(). It stops scaling around a few thousand conversations; at that point swap the repository forexpo-sqlitebehind the same interface. - Errors with a stable code and copy safe to show.
AppErrorcarriescode,retryableand a user message; HTTP mapping lives in one function. The UI shows the message and a Retry button only when retrying can work. -
FlatListkeyed by message id, withMarkdownViewmemoised per message. A long answer re-renders only the message whose text changed, not the whole list. - Store review notes. If your app creates an account, Apple wants in-app account deletion; if it sells anything, it wants Restore. Put both in the checklist before the first submission, not after a rejection.
If you want the whole thing
Everything above is packaged as Expo AI App Kit — React Native AI Starter: the streaming chat with markdown, onboarding, history and favourites, the plan/paywall pattern with RevenueCat wiring, the demo mode, the Edge/Node proxy, and the docs (architecture, store checklist, ASO copy, troubleshooting). Expo SDK 58, TypeScript strict, 204 unit tests, one npm ci away from running.
- Kit: seoyyy.gumroad.com/l/expo-ai-app-kit — $35, 30-day refund, no questions asked
- Launch code:
LAUNCH30for 30% off at checkout - Everything else I've built: seoyyy.gumroad.com
If you only take the four ideas — parse SSE incrementally, keep streaming state in a reducer, render markdown from your own AST, and put the key and the quota on a server — you can skip most of the surprises that come with shipping an AI app to a phone.

