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

react-native.md

146 lines4.4 KB

1---
2title: React Native
3id: transports-react-native
4order: 5
5description: "Stream chat in React Native and Expo with xhrHttpStream or xhrServerSentEvents, and learn when fetchHttpStream works on mobile."
6keywords:
7 - tanstack ai
8 - react native
9 - expo
10 - xhrHttpStream
11 - xhrServerSentEvents
12 - fetchHttpStream
13 - UnsupportedResponseStreamError
14 - mobile streaming
15---
16​
17Use `useChat` from `@tanstack/ai-react` with `xhrHttpStream()` and an absolute URL. XHR progress events carry the stream when `fetch` streaming is missing.
18​
19## Quick setup
20​
21### 1. Return NDJSON from the server
22​
23Your backend returns the stream with `toHttpResponse()`:
24​
25```typescript
26// server route: POST /chat/http
27import { chat, chatParamsFromRequest, toHttpResponse } from "@tanstack/ai";
28import { openaiText } from "@tanstack/ai-openai";
29​
30export async function POST(request: Request) {
31 const { messages, threadId, runId } = await chatParamsFromRequest(request);
32 const stream = chat({
33 adapter: openaiText("gpt-6.1-sol"),
34 messages,
35 threadId,
36 runId,
37 });
38 return toHttpResponse(stream);
40```
41​
42### 2. Set the backend URL
43​
44Put the backend address in a public Expo variable:
45​
46```env
47EXPO_PUBLIC_TANSTACK_AI_BASE_URL=http://127.0.0.1:8787
48```
49​
50Use a URL that your runtime can reach:
51​
52- **iOS simulator**: usually `localhost` or `127.0.0.1`.
53- **Android emulator**: usually `10.0.2.2`, to reach the host machine.
54- **A physical device**: a LAN URL or a tunnel URL.
55​
56### 3. Connect with `xhrHttpStream`
57​
58```tsx
59import { Button, Text, View } from "react-native";
60import { useChat, xhrHttpStream } from "@tanstack/ai-react";
61​
62const baseUrl =
63 process.env.EXPO_PUBLIC_TANSTACK_AI_BASE_URL ?? "http://127.0.0.1:8787";
64​
65export function ChatScreen() {
66 const { messages, sendMessage } = useChat({
67 connection: xhrHttpStream(`${baseUrl}/chat/http`),
68 threadId: "support-chat",
69 });
70​
71 return (
72 <View>
73 {messages.map((message) => (
74 <Text key={message.id}>
75 {message.parts.map((part) =>
76 part.type === "text" ? part.content : "",
77 )}
78 </Text>
79 ))}
80 <Button title="Send" onPress={() => void sendMessage("Hello")} />
81 </View>
82 );
84```
85​
86Tap Send in the simulator. The reply streams into `messages` as the model writes it.
87​
88For a full mobile walkthrough with a Hono server and a text input, see [Quick Start: React Native](../getting-started/quick-start-react-native).
89​
90## How it works
91​
921. `sendMessage` posts the messages to your backend through XHR.
932. The server writes each chunk as one line of JSON.
943. `xhrHttpStream()` reads new lines from each XHR progress event and updates `messages`.
95​
96Mobile connections drop often. If the server adds a durability adapter, both XHR transports reconnect and support `joinRun`. See [Resumable Streams](../resumable-streams/overview).
97​
98## Advanced
99​
100### Use SSE on mobile
101​
102If your server returns `text/event-stream` with `toServerSentEventsResponse()` (see [Server-Sent Events](./sse)), use `xhrServerSentEvents()`:
103​
104```typescript
105import { xhrServerSentEvents } from "@tanstack/ai-react";
106​
107const baseUrl =
108 process.env.EXPO_PUBLIC_TANSTACK_AI_BASE_URL ?? "http://127.0.0.1:8787";
109​
110export const connection = xhrServerSentEvents(`${baseUrl}/chat/sse`);
111```
112​
113Pass this `connection` to `useChat`.
114​
115### Use `fetchHttpStream` on mobile
116​
117`fetchHttpStream()` works only if your React Native runtime has all of these:
118​
119- Streaming `fetch` responses.
120- `Response.body.getReader()`.
121- `TextDecoder`.
122​
123The server still returns newline-delimited JSON with `toHttpResponse()`:
124​
125```typescript
126import { fetchHttpStream } from "@tanstack/ai-react";
127​
128const baseUrl =
129 process.env.EXPO_PUBLIC_TANSTACK_AI_BASE_URL ?? "http://127.0.0.1:8787";
130​
131export const connection = fetchHttpStream(`${baseUrl}/chat/http`);
132```
133​
134If one of these APIs is missing, `fetchHttpStream()` throws `UnsupportedResponseStreamError`. A polyfill that buffers the response does not help, because the transport needs incremental bytes. Use `xhrHttpStream()` or `xhrServerSentEvents()`.
135​
136### Request options on mobile
137​
138The XHR transports take `headers` and `body`, like the fetch transports. For cookies, they use `withCredentials`, not `credentials`. See [Request Options](./request-options).
139​
140### Keep the bundle small
141​
142Keep provider SDKs and server helpers on your backend. Import only hooks and connection adapters in the React Native bundle. Do not import these:
143​
144- OpenAI, Anthropic, or Gemini SDKs.
145- React DOM UI or devtools UI.
146- Packages for other frameworks.