Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

quick-start-react-native.md

314 lines9.7 KB

1---
2title: "Quick Start: React Native"
3id: quick-start-react-native
4order: 3
5description: "Build a React Native or Expo chat screen with TanStack AI's useChat hook, a server-only OpenAI backend, and mobile-compatible streaming transports."
6keywords:
7 - tanstack ai
8 - react native
9 - expo
10 - mobile
11 - useChat
12 - streaming
13 - xhrHttpStream
14 - openai
15---
16​
17You have a React Native or Expo app and you want to add streaming AI chat
18without putting provider SDKs or API keys in the native bundle. By the end of
19this guide, your app will call a server-owned Hono route with `useChat` from
20`@tanstack/ai-react`, stream responses over a mobile-compatible transport, and
21keep `OPENAI_API_KEY` / `OPENAI_MODEL` on the server.
22​
23> **Coming from the web quick start?** The hook is the same, but the URL and
24> transport are different. React Native needs an absolute backend URL, not
25> `/api/chat`, and most Expo runtimes should start with `xhrHttpStream()`.
26​
27## 1. Install packages
28​
29If you are starting from scratch, create an Expo app first:
30​
31<!-- ::start:tabs variant="package-manager" mode="local-install" -->
32​
33react: create-expo-app@latest my-ai-chat
34​
35<!-- ::end:tabs -->
36​
37Install TanStack AI, the React hook package, the OpenAI adapter for your
38server, and Hono for the example backend:
39​
40<!-- ::start:tabs variant="package-manager" mode="install" -->
41​
42react: @tanstack/ai @tanstack/ai-react @tanstack/ai-openai hono @hono/node-server zod
43​
44<!-- ::end:tabs -->
45​
46If your Expo app lives in a workspace, run the command from the app package or
47use your workspace filter.
48​
49## 2. Keep OpenAI on the server
50​
51Create a Hono route that owns the model, API key, and response format. The
52native app sends chat messages to this route; it never imports
53`@tanstack/ai-openai` and never receives `OPENAI_API_KEY`.
54​
55```ts
56// server.ts
57import { serve } from '@hono/node-server'
58import { chat, toHttpResponse, toServerSentEventsResponse } from '@tanstack/ai'
59import { openaiText } from '@tanstack/ai-openai'
60import { Hono } from 'hono'
61import { model } from './config'
62​
63const app = new Hono()
64​
65function requireOpenAIKey() {
66 if (!process.env.OPENAI_API_KEY) {
67 throw new Error('OPENAI_API_KEY is not configured on the server')
68 }
70​
71app.get('/health', (c) => c.json({ ok: true }))
72​
73app.post('/chat/http', async (c) => {
74 requireOpenAIKey()
75 const body = await c.req.json()
76 const stream = chat({
77 adapter: openaiText(model),
78 messages: body.messages,
79 })
80​
81 return toHttpResponse(stream, {
82 headers: {
83 'Content-Type': 'application/x-ndjson',
84 'Cache-Control': 'no-cache',
85 },
86 })
87})
88​
89app.post('/chat/sse', async (c) => {
90 requireOpenAIKey()
91 const body = await c.req.json()
92 const stream = chat({
93 adapter: openaiText(model),
94 messages: body.messages,
95 })
96​
97 return toServerSentEventsResponse(stream)
98})
99​
100serve({
101 fetch: app.fetch,
102 hostname: '0.0.0.0',
103 port: Number(process.env.PORT ?? 8787),
104})
105```
106​
107Set server-only environment variables where the Hono process runs:
108​
109```env
110OPENAI_API_KEY=sk-...
111OPENAI_MODEL=gpt-5.2
112```
113​
114Run the Hono server before starting the native app. For a TypeScript-only
115example, install `tsx` and add a script:
116​
117<!-- ::start:tabs variant="package-manager" mode="dev-install" -->
118​
119react: tsx
120​
121<!-- ::end:tabs -->
122​
123```bash
124pnpm pkg set scripts.dev:server="tsx server.ts"
125pnpm dev:server
126```
127​
128> **Route pairing matters:** `xhrHttpStream()` and `fetchHttpStream()` expect
129> the newline-delimited JSON response from `toHttpResponse()`.
130> `xhrServerSentEvents()` expects the `text/event-stream` response from
131> `toServerSentEventsResponse()`.
132​
133## 3. Configure a native-reachable URL
134​
135React Native is not served from your backend origin, so `/api/chat` cannot work
136as a default. Expose the backend URL to Expo with a public variable:
137​
138```env
139EXPO_PUBLIC_TANSTACK_AI_BASE_URL=http://192.168.1.10:8787
140```
141​
142Use the address your device can reach:
143​
144- iOS simulator: `http://127.0.0.1:8787` often works.
145- Android emulator: use `http://10.0.2.2:8787`.
146- Physical device: use your computer's LAN IP, for example
147 `http://192.168.1.10:8787`, or a tunneled HTTPS URL.
148​
149Only `EXPO_PUBLIC_*` values are bundled into the app. Keep provider keys as
150plain server variables such as `OPENAI_API_KEY`.
151​
152## 4. Use `useChat` in your native screen
153​
154Start with `xhrHttpStream()` for Expo and React Native. It reads the same
155newline-delimited JSON produced by `toHttpResponse()` and relies on XHR progress
156events, which are usually more reliable on phone runtimes than streaming
157`fetch`.
158​
159```tsx
160// ChatScreen.tsx
161import { useState } from 'react'
162import { Button, ScrollView, Text, TextInput, View } from 'react-native'
163import { useChat, xhrHttpStream } from '@tanstack/ai-react'
164​
165const baseUrl =
166 process.env.EXPO_PUBLIC_TANSTACK_AI_BASE_URL ?? 'http://127.0.0.1:8787'
167​
168export function ChatScreen() {
169 const [input, setInput] = useState('')
170 const { messages, sendMessage, isLoading, error } = useChat({
171 connection: xhrHttpStream(`${baseUrl}/chat/http`),
172 })
173​
174 async function send() {
175 const text = input.trim()
176 if (!text || isLoading) return
177 setInput('')
178 await sendMessage(text)
179 }
180​
181 return (
182 <View style={{ flex: 1, padding: 24, gap: 12 }}>
183 <ScrollView style={{ flex: 1 }}>
184 {messages.map((message) => (
185 <View key={message.id} style={{ marginBottom: 16 }}>
186 <Text style={{ fontWeight: '700' }}>{message.role}</Text>
187 {message.parts.map((part, index) =>
188 part.type === 'text' ? (
189 <Text key={index}>{part.content}</Text>
190 ) : null,
191 )}
192 </View>
193 ))}
194 </ScrollView>
195​
196 {error ? <Text style={{ color: 'crimson' }}>{error.message}</Text> : null}
197​
198 <TextInput
199 value={input}
200 onChangeText={setInput}
201 editable={!isLoading}
202 placeholder="Ask for a recipe..."
203 style={{ borderWidth: 1, borderRadius: 8, padding: 12 }}
204 />
205 <Button title={isLoading ? 'Streaming...' : 'Send'} onPress={send} />
206 </View>
207 )
209```
210​
211You now have a native chat screen that calls your server endpoint, streams
212assistant text, and keeps provider credentials outside the app.
213​
214## 5. Choose a transport deliberately
215​
216Use the transport that matches your server route and runtime:
217​
218| Native runtime | Client adapter | Server response |
219| --- | --- | --- |
220| Most Expo / React Native apps | `xhrHttpStream(url)` with `/chat/http` | `toHttpResponse(stream)` |
221| SSE-compatible native runtime or proxy path | `xhrServerSentEvents(url)` with `/chat/sse` | `toServerSentEventsResponse(stream)` |
222| Runtime with streaming `fetch` support | `fetchHttpStream(url)` with `/chat/http` | `toHttpResponse(stream)` |
223​
224Only use `fetchHttpStream()` when your exact runtime supports all of:
225​
226- `Response.body`
227- `Response.body.getReader()`
228- `TextDecoder`
229​
230If any of those are missing, the adapter throws
231`UnsupportedResponseStreamError`. A polyfilled `fetch` that buffers the whole
232response is not enough; TanStack AI needs incremental response bytes to update
233the chat while the model is streaming.
234​
235For deeper adapter options such as headers, credentials, `withCredentials`, and
236dynamic URLs, see [Request Options](../transports/request-options).
237​
238## 6. Try the Expo recipe example
239​
240If you are evaluating React Native support, use the included Expo app. It runs a
241local Hono/OpenAI server, shows a transport selector, and streams structured
242recipe cards so you can verify native chat and structured output behavior
243together.
244​
245Create `examples/ts-react-native-chat/.env`:
246​
247```env
248OPENAI_API_KEY=sk-...
249OPENAI_MODEL=gpt-5.2
250```
251​
252Run the example:
253​
254```bash
255pnpm --filter ts-react-native-chat dev
256```
257​
258The command starts:
259​
260- Hono on `0.0.0.0:8787`
261- Expo/Metro in LAN mode
262- `EXPO_PUBLIC_TANSTACK_AI_BASE_URL=http://<lan-ip>:8787` when a LAN address is detected
263​
264Scan the Expo Go QR code from a phone on the same Wi-Fi network. In the app,
265use the Testing mode panel to switch between Fetch HTTP, XHR HTTP, and XHR SSE.
266The main recipe card streams structured fields such as title, ingredients,
267steps, tips, warnings, and revision across follow-up prompts.
268​
269For example-specific commands and network overrides, see
270`examples/ts-react-native-chat/README.md`.
271​
272## Troubleshooting
273​
274### `http://localhost:8081` shows JSON
275​
276That is normal. Port `8081` is Metro's manifest and bundle server, not a web UI.
277Launch the app from Expo Go, an Android emulator, or an iOS simulator instead.
278​
279### A physical device cannot reach the backend
280​
281Open `http://<lan-ip>:8787/health` from the phone browser. If it does not return
282`{"ok":true}`, confirm the phone and computer are on the same Wi-Fi network,
283client isolation is disabled, and your firewall allows Node.js on the Hono port
284and Metro port `8081`.
285​
286### Android emulator cannot reach `127.0.0.1`
287​
288Use `http://10.0.2.2:8787` for
289`EXPO_PUBLIC_TANSTACK_AI_BASE_URL`. Android emulators map `10.0.2.2` to the
290host machine.
291​
292### Expo prints Android SDK or `adb` warnings
293​
294This is an Android tooling issue, not a TanStack AI transport issue. Confirm
295Android Studio installed the SDK, an emulator exists in Device Manager, and
296`adb` is on `PATH`. On Windows, check
297`%LOCALAPPDATA%\Android\Sdk\platform-tools\adb.exe`.
298​
299### The phone logs `UnsupportedResponseStreamError`
300​
301Your runtime does not expose streaming `fetch`, `Response.body.getReader()`, or
302`TextDecoder`. Switch from `fetchHttpStream()` to `xhrHttpStream()` or
303`xhrServerSentEvents()`. Do not rely on fetch polyfills unless they provide a
304real incremental readable stream.
305​
306### XHR reports a server error
307​
308Check the Hono server terminal first. Common causes are missing
309`OPENAI_API_KEY`, an unsupported `OPENAI_MODEL`, or pointing
310`xhrServerSentEvents()` at `/chat/http` instead of `/chat/sse` (or the reverse).
311​
312You now have the full React Native path: a server-owned provider boundary, a
313native-reachable URL, a mobile-compatible transport, and an Expo example that
314proves the setup on a real device.