Open History to see the last commit
1---
2title: "Quick Start: React"
3id: quick-start
4order: 2
5description: "Add a streaming TanStack AI chat to a React app in minutes using the useChat hook and the OpenAI adapter."
6keywords:
7 - tanstack ai
8 - react
9 - quick start
10 - useChat
11 - streaming chat
12 - openai
13 - tutorial
14 - ai chatbot
15---
16
17Get started with TanStack AI in minutes. This guide will walk you through creating a simple chat application using the React integration and OpenAI adapter.
18
19> **Using a different framework?** See quick-starts for [Vue](./quick-start-vue), [Svelte](./quick-start-svelte), or [server-only Node.js](./quick-start-server).
20
21> **React Native or Expo app?** Use the headless React hooks with an absolute
22> server URL and a mobile-compatible transport. See
23> [Quick Start: React Native](./quick-start-react-native).
24
25> **Tip:** If you'd prefer not to sign up with individual AI providers, [OpenRouter](../adapters/openrouter) gives you access to 300+ models with a single API key and is the easiest way to get started.
26
27## Installation
28
29```bash
30npm install @tanstack/ai @tanstack/ai-react @tanstack/ai-openai
31# or
32pnpm add @tanstack/ai @tanstack/ai-react @tanstack/ai-openai
33#or
34yarn add @tanstack/ai @tanstack/ai-react @tanstack/ai-openai
35```
36
37## Server Setup
38
39First, create an API route that handles chat requests. Here's a simplified example:
40
41### TanStack Start
42
43```typescript ignore
44import { chat, toServerSentEventsResponse } from "@tanstack/ai";
45import { openaiText } from "@tanstack/ai-openai";
46import { createFileRoute } from "@tanstack/react-router";
47
48export const Route = createFileRoute("/api/chat")({
49 server: {
50 handlers: {
51 POST: async ({ request }) => {
52 // Check for API key
53 if (!process.env.OPENAI_API_KEY) {
54 return new Response(
55 JSON.stringify({
56 error: "OPENAI_API_KEY not configured",
57 }),
58 {
59 status: 500,
60 headers: { "Content-Type": "application/json" },
61 },
62 );
63 }
64
65 const body = await request.json();
66
67 try {
68 // Create a streaming chat response. `chat()` reads the AG-UI
69 // `threadId` for devtools correlation when available.
70 const stream = chat({
71 adapter: openaiText("gpt-5.5"),
72 messages: body.messages,
73 });
74
75 // Convert stream to HTTP response
76 return toServerSentEventsResponse(stream);
77 } catch (error) {
78 return new Response(
79 JSON.stringify({
80 error:
81 error instanceof Error ? error.message : "An error occurred",
82 }),
83 {
84 status: 500,
85 headers: { "Content-Type": "application/json" },
86 },
87 );
88 }
89 },
90 },
91 },
92});
93```
94
95### Next.js
96
97```typescript
98import { chat, toServerSentEventsResponse } from "@tanstack/ai";
99import { openaiText } from "@tanstack/ai-openai";
100
101export async function POST(request: Request) {
102 // Check for API key
103 if (!process.env.OPENAI_API_KEY) {
104 return new Response(
105 JSON.stringify({
106 error: "OPENAI_API_KEY not configured",
107 }),
108 {
109 status: 500,
110 headers: { "Content-Type": "application/json" },
111 }
112 );
113 }
114
115 const body = await request.json();
116
117 try {
118 // Create a streaming chat response. `chat()` reads the AG-UI
119 // `threadId` for devtools correlation when available.
120 const stream = chat({
121 adapter: openaiText("gpt-5.5"),
122 messages: body.messages,
123 });
124
125 // Convert stream to HTTP response
126 return toServerSentEventsResponse(stream);
127 } catch (error) {
128 return new Response(
129 JSON.stringify({
130 error: error instanceof Error ? error.message : "An error occurred",
131 }),
132 {
133 status: 500,
134 headers: { "Content-Type": "application/json" },
135 }
136 );
137 }
138}
139```
140
141## Client Setup
142
143To use the chat API from your React frontend, create a `Chat` component:
144
145```tsx
146// components/Chat.tsx
147import { useState } from "react";
148import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
149
150export function Chat() {
151 const [input, setInput] = useState("");
152
153 const { messages, sendMessage, isLoading, error } = useChat({
154 connection: fetchServerSentEvents("/api/chat"),
155 });
156
157 const handleSubmit = (e: React.FormEvent) => {
158 e.preventDefault();
159 if (input.trim() && !isLoading) {
160 sendMessage(input);
161 setInput("");
162 }
163 };
164
165 return (
166 <div className="flex flex-col h-screen">
167 {/* Messages */}
168 <div className="flex-1 overflow-y-auto p-4">
169 {messages.map((message) => (
170 <div
171 key={message.id}
172 className={`mb-4 ${
173 message.role === "assistant" ? "text-blue-600" : "text-gray-800"
174 }`}
175 >
176 <div className="font-semibold mb-1">
177 {message.role === "assistant" ? "Assistant" : "You"}
178 </div>
179 <div>
180 {message.parts.map((part, idx) => {
181 if (part.type === "thinking") {
182 return (
183 <div
184 key={idx}
185 className="text-sm text-gray-500 italic mb-2"
186 >
187 💭 Thinking: {part.content}
188 </div>
189 );
190 }
191 if (part.type === "text") {
192 return <div key={idx}>{part.content}</div>;
193 }
194 return null;
195 })}
196 </div>
197 </div>
198 ))}
199 </div>
200
201 {/* Error */}
202 {error && (
203 <p role="alert" className="px-4 text-red-600">
204 {error.message}
205 </p>
206 )}
207
208 {/* Input */}
209 <form onSubmit={handleSubmit} className="p-4 border-t">
210 <div className="flex gap-2">
211 <input
212 type="text"
213 value={input}
214 onChange={(e) => setInput(e.target.value)}
215 placeholder="Type a message..."
216 className="flex-1 px-4 py-2 border rounded-lg"
217 disabled={isLoading}
218 />
219 <button
220 type="submit"
221 disabled={!input.trim() || isLoading}
222 className="px-6 py-2 bg-blue-600 text-white rounded-lg disabled:opacity-50"
223 >
224 Send
225 </button>
226 </div>
227 </form>
228 </div>
229 );
230}
231```
232
233## Environment Variables
234
235To connect to AI providers, set your API keys in your environment variables. Create a `.env.local` file (or `.env` depending on your setup):
236```bash
237# OpenRouter (recommended — access 300+ models with one key)
238OPENROUTER_API_KEY=sk-or-...
239
240# OpenAI
241OPENAI_API_KEY=your-openai-api-key
242
243# Anthropic
244ANTHROPIC_API_KEY=your-anthropic-api-key
245
246# Google Gemini
247GEMINI_API_KEY=your-gemini-api-key
248```
249
250## That's It!
251
252You now have a working chat application. The `useChat` hook handles:
253
254- Message state management
255- Streaming responses
256- Loading states
257- Error handling
258
259## Using Tools
260
261Since TanStack AI is framework-agnostic, you can define and use tools in any environment. Here's a quick example of defining a tool and using it in a chat:
262
263```typescript
264import { chat, toolDefinition } from '@tanstack/ai'
265import { openaiText } from '@tanstack/ai-openai'
266import { z } from 'zod'
267import { db } from './db'
268
269const getProductsDef = toolDefinition({
270 name: 'getProducts',
271 description: 'Search the product catalog',
272 inputSchema: z.object({ query: z.string() }),
273 outputSchema: z.array(z.object({ id: z.string(), name: z.string() })),
274})
275
276const getProducts = getProductsDef.server(async ({ query }) => {
277 return await db.products.search(query)
278})
279
280const stream = chat({
281 adapter: openaiText('gpt-5.5'),
282 messages: [{ role: 'user', content: 'Find products' }],
283 tools: [getProducts],
284})
285```
286
287## Next Steps
288
289- Learn about [Tools](../tools/tools) to add function calling
290- Check out [Client Tools](../tools/client-tools) for frontend operations
291- See the [API Reference](../api/ai) for more options