Open History to see the last commit
1---
2title: "Quick Start: React Native"
3id: quick-start-react-native
4order: 3
5description: "Add a streaming chat screen to a React Native or Expo app with useChat. The OpenAI key stays on your server, and the app streams over XHR."
6keywords:
7 - tanstack ai
8 - react native
9 - expo
10 - mobile
11 - useChat
12 - streaming
13 - xhrHttpStream
14 - openai
15---
16
17This guide adds a streaming chat to a React Native or Expo app. The provider key stays on your server.
18
19Put the model behind a small server route. The app calls it with `useChat` from `@tanstack/ai-react` and streams over XHR. This takes about 10 minutes.
20
21Two things differ from the [web Quick Start](./quick-start):
22
23- **The URL is absolute.** The app is not served from your backend, so `/api/chat` does not work.
24- **The transport is XHR.** Start with `xhrHttpStream()`. Streaming `fetch` is often missing on phones.
25
26## 1. Install
27
28If you start from scratch, create an Expo app first:
29
30<!-- ::start:tabs variant="package-manager" mode="local-install" -->
31
32react: create-expo-app@latest my-ai-chat
33
34<!-- ::end:tabs -->
35
36Install TanStack AI, the React hooks, the OpenAI adapter for the server, and Hono for the example server:
37
38<!-- ::start:tabs variant="package-manager" mode="install" -->
39
40react: @tanstack/ai @tanstack/ai-react @tanstack/ai-openai hono @hono/node-server zod
41
42<!-- ::end:tabs -->
43
44If your Expo app is in a workspace, run the command from the app package, or use your workspace filter.
45
46## 2. Create the server
47
48The server owns the model and the API key. The native app never imports `@tanstack/ai-openai` and never sees `OPENAI_API_KEY`.
49
50Create `server.ts`:
51
52```ts
53import { serve } from '@hono/node-server'
54import { chat, toHttpResponse } from '@tanstack/ai'
55import { openaiText } from '@tanstack/ai-openai'
56import { Hono } from 'hono'
57
58const app = new Hono()
59
60app.get('/health', (c) => c.json({ ok: true }))
61
62app.post('/chat/http', async (c) => {
63 if (!process.env.OPENAI_API_KEY) {
64 throw new Error('OPENAI_API_KEY is not configured on the server')
65 }
66 const body = await c.req.json()
67 const stream = chat({
68 adapter: openaiText('gpt-6.1-sol'),
69 messages: body.messages,
70 threadId: body.threadId,
71 })
72
73 return toHttpResponse(stream, {
74 headers: {
75 'Content-Type': 'application/x-ndjson',
76 'Cache-Control': 'no-cache',
77 },
78 })
79})
80
81serve({
82 fetch: app.fetch,
83 hostname: '0.0.0.0',
84 port: Number(process.env.PORT ?? 8787),
85})
86```
87
88Set the key where the Hono process runs:
89
90```env
91OPENAI_API_KEY=sk-...
92```
93
94## 3. Start the server
95
96Install `tsx` to run the TypeScript file:
97
98<!-- ::start:tabs variant="package-manager" mode="dev-install" -->
99
100react: tsx
101
102<!-- ::end:tabs -->
103
104Add a script and run it:
105
106```bash
107pnpm pkg set scripts.dev:server="tsx server.ts"
108pnpm dev:server
109```
110
111Keep the server running while you use the app.
112
113## 4. Set the server URL
114
115Give Expo the server address in a public variable:
116
117```env
118EXPO_PUBLIC_TANSTACK_AI_BASE_URL=http://192.168.1.10:8787
119```
120
121Use an address that your device can reach:
122
123- **iOS simulator:** `http://127.0.0.1:8787` often works.
124- **Android emulator:** `http://10.0.2.2:8787`.
125- **Physical device:** the LAN IP of your computer, for example `http://192.168.1.10:8787`, or a tunneled HTTPS URL.
126
127Expo bundles only `EXPO_PUBLIC_*` values into the app. Keep provider keys as plain server variables, such as `OPENAI_API_KEY`.
128
129## 5. Add the chat screen
130
131Create `ChatScreen.tsx`:
132
133```tsx
134import { useState } from 'react'
135import { Button, ScrollView, Text, TextInput, View } from 'react-native'
136import { useChat, xhrHttpStream } from '@tanstack/ai-react'
137
138const baseUrl =
139 process.env.EXPO_PUBLIC_TANSTACK_AI_BASE_URL ?? 'http://127.0.0.1:8787'
140
141export function ChatScreen() {
142 const [input, setInput] = useState('')
143 const { messages, sendMessage, isLoading, error } = useChat({
144 connection: xhrHttpStream(`${baseUrl}/chat/http`),
145 threadId: 'support-chat',
146 })
147
148 async function send() {
149 const text = input.trim()
150 if (!text || isLoading) return
151 setInput('')
152 await sendMessage(text)
153 }
154
155 return (
156 <View style={{ flex: 1, padding: 24, gap: 12 }}>
157 <ScrollView style={{ flex: 1 }}>
158 {messages.map((message) => (
159 <View key={message.id} style={{ marginBottom: 16 }}>
160 <Text style={{ fontWeight: '700' }}>{message.role}</Text>
161 {message.parts.map((part, index) =>
162 part.type === 'text' ? (
163 <Text key={index}>{part.content}</Text>
164 ) : null,
165 )}
166 </View>
167 ))}
168 </ScrollView>
169
170 {error ? <Text style={{ color: 'crimson' }}>{error.message}</Text> : null}
171
172 <TextInput
173 value={input}
174 onChangeText={setInput}
175 editable={!isLoading}
176 placeholder="Ask for a recipe..."
177 style={{ borderWidth: 1, borderRadius: 8, padding: 12 }}
178 />
179 <Button title={isLoading ? 'Streaming...' : 'Send'} onPress={send} />
180 </View>
181 )
182}
183```
184
185## 6. Try it
186
187Render `ChatScreen` in your app and open it on a device or simulator. Send a message. The answer streams in, and the provider key stays on the server.
188
189## How it works
190
1911. `sendMessage` posts the messages to `/chat/http` through `xhrHttpStream()`.
1922. The Hono route calls `chat()` and returns newline-delimited JSON with `toHttpResponse()`.
1933. `xhrHttpStream()` reads the response through XHR progress events and updates `messages` as chunks arrive.
194
195XHR progress events are usually more reliable on phone runtimes than streaming `fetch`.
196
197> [!NOTE]
198> Each client transport expects one server response format. `xhrHttpStream()` and `fetchHttpStream()` read the newline-delimited JSON from `toHttpResponse()`. `xhrServerSentEvents()` reads the `text/event-stream` from `toServerSentEventsResponse()`.
199
200## Advanced
201
202### Choose a transport
203
204Use the transport that matches your server route and your runtime:
205
206| Native runtime | Client adapter | Server response |
207| --- | --- | --- |
208| Most Expo and React Native apps | `xhrHttpStream(url)` with `/chat/http` | `toHttpResponse(stream)` |
209| A runtime or proxy path that supports SSE | `xhrServerSentEvents(url)` with `/chat/sse` | `toServerSentEventsResponse(stream)` |
210| A runtime with streaming `fetch` | `fetchHttpStream(url)` with `/chat/http` | `toHttpResponse(stream)` |
211
212To serve SSE, add this route to `server.ts` and import `toServerSentEventsResponse` from `@tanstack/ai`:
213
214```ts ignore
215app.post('/chat/sse', async (c) => {
216 const body = await c.req.json()
217 const stream = chat({
218 adapter: openaiText('gpt-6.1-sol'),
219 messages: body.messages,
220 threadId: body.threadId,
221 })
222
223 return toServerSentEventsResponse(stream)
224})
225```
226
227Use `fetchHttpStream()` only when your runtime supports all of these:
228
229- `Response.body`
230- `Response.body.getReader()`
231- `TextDecoder`
232
233If one of them is missing, the adapter throws `UnsupportedResponseStreamError`. A polyfilled `fetch` that buffers the whole response is not enough. TanStack AI needs the response bytes as they arrive to update the chat during the stream.
234
235For headers, credentials, `withCredentials`, and dynamic URLs, see [Request Options](../transports/request-options).
236
237### Run the Expo recipe example
238
239The repo has an Expo app for React Native. It runs a local Hono and OpenAI server, has a transport selector, and streams structured recipe cards. Use it to test native chat and structured output together.
240
2411. Create `examples/ts-react-native-chat/.env`:
242
243 ```env
244 OPENAI_API_KEY=sk-...
245 OPENAI_MODEL=gpt-5.2
246 ```
247
2482. Run the example:
249
250 ```bash
251 pnpm --filter ts-react-native-chat dev
252 ```
253
254 The command starts:
255
256 - Hono on `0.0.0.0:8787`.
257 - Expo and Metro in LAN mode.
258 - `EXPO_PUBLIC_TANSTACK_AI_BASE_URL=http://<lan-ip>:8787`, when it finds a LAN address.
259
2603. Scan the Expo Go QR code from a phone on the same Wi-Fi network.
261
262In the app, use the Testing mode panel to switch between Fetch HTTP, XHR HTTP, and XHR SSE. The recipe card streams structured fields: title, ingredients, steps, tips, warnings, and revision. Follow-up prompts revise the same recipe.
263
264For commands and network overrides, see `examples/ts-react-native-chat/README.md`.
265
266### Troubleshooting
267
268**`http://localhost:8081` shows JSON.** This is correct. Port `8081` is the Metro manifest and bundle server, not a web UI. Open the app from Expo Go, an Android emulator, or an iOS simulator.
269
270**A physical device cannot reach the backend.** Open `http://<lan-ip>:8787/health` in the phone browser. If it does not return `{"ok":true}`, make sure that:
271
272- The phone and the computer are on the same Wi-Fi network.
273- Client isolation is off on the network.
274- Your firewall lets Node.js use the Hono port and Metro port `8081`.
275
276**The Android emulator cannot reach `127.0.0.1`.** Set `EXPO_PUBLIC_TANSTACK_AI_BASE_URL` to `http://10.0.2.2:8787`. Android emulators map `10.0.2.2` to the host machine.
277
278**Expo prints Android SDK or `adb` warnings.** This is an Android tooling error, not a TanStack AI transport error. Make sure that:
279
280- Android Studio installed the SDK.
281- An emulator exists in Device Manager.
282- `adb` is on `PATH`. On Windows, look for `%LOCALAPPDATA%\Android\Sdk\platform-tools\adb.exe`.
283
284**The phone logs `UnsupportedResponseStreamError`.** Your runtime does not have streaming `fetch`, `Response.body.getReader()`, or `TextDecoder`. Switch from `fetchHttpStream()` to `xhrHttpStream()` or `xhrServerSentEvents()`. Fetch polyfills work only if they give a real incremental readable stream.
285
286**XHR reports a server error.** Read the Hono server terminal first. The usual causes:
287
288- `OPENAI_API_KEY` is missing.
289- `OPENAI_MODEL` names a model that the adapter does not support (in the example app).
290- `xhrServerSentEvents()` points at `/chat/http` instead of `/chat/sse`, or the reverse.