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

quick-start-react-native.md

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