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