Open History to see the last commit
1---
2title: Quick Start
3id: quick-start
4order: 2
5description: "Add a streaming TanStack AI chat to your app. Pick a framework, install, stream from a server route, and render with the matching hook."
6keywords:
7 - tanstack ai
8 - quick start
9 - useChat
10 - injectChat
11 - createChat
12 - streaming chat
13 - openai
14 - react
15 - vue
16 - solid
17 - svelte
18 - preact
19 - angular
20 - octane
21 - remix
22redirect_from:
23 - /getting-started/quick-start-vue
24 - /getting-started/quick-start-svelte
25 - /getting-started/quick-start-angular
26 - /getting-started/quick-start-octane
27---
28
29This guide adds a chat that renders tokens while the model writes them. You add a server route, an API key, and a UI.
30
31TanStack AI gives you each piece. `chat()` streams from your server route. A hook for your framework renders the tokens. This takes about 5 minutes.
32
33Not on the web?
34
35- **React Native or Expo:** go to [Quick Start: React Native](./quick-start-react-native).
36- **No UI, only a backend:** go to [Quick Start: Server Only](./quick-start-server).
37
38## 1. Install
39
40<!-- ::start:tabs variant="package-manager" mode="install" -->
41
42react: @tanstack/ai @tanstack/ai-react @tanstack/ai-openai
43vue: @tanstack/ai @tanstack/ai-vue @tanstack/ai-openai
44solid: @tanstack/ai @tanstack/ai-solid @tanstack/ai-openai
45svelte: @tanstack/ai @tanstack/ai-svelte @tanstack/ai-openai
46preact: @tanstack/ai @tanstack/ai-preact @tanstack/ai-openai
47angular: @tanstack/ai @tanstack/ai-angular @tanstack/ai-openai
48vanilla: @tanstack/ai @tanstack/ai-client @tanstack/ai-openai
49octane: @tanstack/ai @tanstack/ai-octane @tanstack/ai-openai octane
50remix: @tanstack/ai @tanstack/ai-remix @tanstack/ai-openai remix
51
52<!-- ::end:tabs -->
53
54Pick your framework at the top of the page. The install command and the UI code follow your pick.
55
56> [!TIP]
57> If you do not want a key for each provider, use [OpenRouter](../adapters/openrouter). It gives you 300+ models with one API key.
58
59## 2. Stream from the server
60
61Put your API key in the server environment, for example in `.env`:
62
63```bash
64OPENAI_API_KEY=your-openai-api-key
65```
66
67Create a route at `/api/chat`. In Next.js, that is `app/api/chat/route.ts`. Call `chat()`, then return the stream with `toServerSentEventsResponse`:
68
69```typescript
70import {
71 chat,
72 chatParamsFromRequest,
73 toServerSentEventsResponse,
74} from "@tanstack/ai";
75import { openaiText } from "@tanstack/ai-openai";
76
77export async function POST(request: Request) {
78 const { messages, threadId, runId } = await chatParamsFromRequest(request);
79
80 const stream = chat({
81 adapter: openaiText("gpt-6.1-sol"),
82 messages,
83 threadId,
84 runId,
85 });
86
87 return toServerSentEventsResponse(stream);
88}
89```
90
91The adapter reads `OPENAI_API_KEY` at runtime. Do not send this key to the browser.
92
93## 3. Render the chat
94
95<!-- ::start:framework -->
96
97# React
98
99Call `useChat` from `@tanstack/ai-react`. Hold the composer text in `useState`. Pass it to `sendMessage`.
100
101```tsx
102import { useState } from "react";
103import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
104
105export function Chat() {
106 const [input, setInput] = useState("");
107 const { messages, sendMessage, isLoading, stop } = useChat({
108 connection: fetchServerSentEvents("/api/chat"),
109 threadId: "support-chat",
110 });
111
112 return (
113 <>
114 {messages.map((message) => (
115 <div key={message.id}>
116 {message.parts.map((part, index) =>
117 part.type === "text" ? <p key={index}>{part.content}</p> : null,
118 )}
119 </div>
120 ))}
121 <form
122 onSubmit={(event) => {
123 event.preventDefault();
124 if (input.trim() === "") {
125 return;
126 }
127 sendMessage(input);
128 setInput("");
129 }}
130 >
131 <input
132 value={input}
133 onChange={(event) => setInput(event.target.value)}
134 />
135 {isLoading ? (
136 <button type="button" onClick={stop}>
137 Stop
138 </button>
139 ) : (
140 <button type="submit">Send</button>
141 )}
142 </form>
143 </>
144 );
145}
146```
147
148`messages` updates as chunks arrive. `isLoading` is `true` while the run is in flight.
149
150See the [React API](../api/ai-react).
151
152# Vue
153
154Call `useChat` from `@tanstack/ai-vue`. If you are in `<script setup>`, read refs with `.value`. The template unwraps them.
155
156```vue
157<script setup lang="ts">
158import { ref } from 'vue'
159import { useChat, fetchServerSentEvents } from '@tanstack/ai-vue'
160
161const input = ref('')
162
163const { messages, sendMessage, isLoading, stop } = useChat({
164 connection: fetchServerSentEvents('/api/chat'),
165 threadId: "support-chat",
166})
167
168function handleSubmit() {
169 if (input.value.trim() && !isLoading.value) {
170 sendMessage(input.value)
171 input.value = ''
172 }
173}
174</script>
175
176<template>
177 <div>
178 <div v-for="message in messages" :key="message.id">
179 <template v-for="(part, index) in message.parts" :key="index">
180 <p v-if="part.type === 'text'">{{ part.content }}</p>
181 </template>
182 </div>
183 <form @submit.prevent="handleSubmit">
184 <input v-model="input" :disabled="isLoading" />
185 <button v-if="isLoading" type="button" @click="stop">Stop</button>
186 <button v-else type="submit" :disabled="!input.trim()">Send</button>
187 </form>
188 </div>
189</template>
190```
191
192The composable stops in-flight requests when the component unmounts.
193
194See the [Vue API](../api/ai-vue).
195
196# Solid
197
198Call `useChat` from `@tanstack/ai-solid`. `messages` and `isLoading` are accessors. Call them as functions.
199
200```tsx ignore
201import { For, createSignal } from "solid-js";
202import { useChat, fetchServerSentEvents } from "@tanstack/ai-solid";
203
204export function Chat() {
205 const [input, setInput] = createSignal("");
206 const { messages, sendMessage, isLoading, stop } = useChat({
207 connection: fetchServerSentEvents("/api/chat"),
208 threadId: "support-chat",
209 });
210
211 return (
212 <>
213 <For each={messages()}>
214 {(message) => (
215 <div>
216 <For each={message.parts}>
217 {(part) =>
218 part.type === "text" ? <p>{part.content}</p> : null
219 }
220 </For>
221 </div>
222 )}
223 </For>
224 <form
225 onSubmit={(event) => {
226 event.preventDefault();
227 if (input().trim() === "") {
228 return;
229 }
230 sendMessage(input());
231 setInput("");
232 }}
233 >
234 <input
235 value={input()}
236 onInput={(event) => setInput(event.currentTarget.value)}
237 />
238 {isLoading() ? (
239 <button type="button" onClick={stop}>
240 Stop
241 </button>
242 ) : (
243 <button type="submit">Send</button>
244 )}
245 </form>
246 </>
247 );
248}
249```
250
251See the [Solid API](../api/ai-solid).
252
253# Svelte
254
255Call `createChat` from `@tanstack/ai-svelte`. The return object uses reactive getters. Read `chat.messages` and `chat.isLoading` with no extra wrapper.
256
257```svelte
258<script lang="ts">
259import { createChat, fetchServerSentEvents } from '@tanstack/ai-svelte'
260
261let input = $state('')
262
263const chat = createChat({
264 connection: fetchServerSentEvents('/api/chat'),
265 threadId: 'support-chat',
266})
267
268function handleSubmit(event: SubmitEvent) {
269 event.preventDefault()
270 if (input.trim() && !chat.isLoading) {
271 chat.sendMessage(input)
272 input = ''
273 }
274}
275</script>
276
277<div>
278 {#each chat.messages as message (message.id)}
279 <div>
280 {#each message.parts as part}
281 {#if part.type === 'text'}
282 <p>{part.content}</p>
283 {/if}
284 {/each}
285 </div>
286 {/each}
287
288 <form onsubmit={handleSubmit}>
289 <input bind:value={input} disabled={chat.isLoading} />
290 {#if chat.isLoading}
291 <button type="button" onclick={() => chat.stop()}>Stop</button>
292 {:else}
293 <button type="submit" disabled={!input.trim()}>Send</button>
294 {/if}
295 </form>
296</div>
297```
298
299If the component can unmount while a response streams, call `chat.stop()` in `onDestroy`.
300
301See the [Svelte API](../api/ai-svelte).
302
303# Preact
304
305Call `useChat` from `@tanstack/ai-preact`. Hold the composer text with `useState` from `preact/hooks`.
306
307```tsx ignore
308import { useState } from "preact/hooks";
309import { useChat, fetchServerSentEvents } from "@tanstack/ai-preact";
310
311export function Chat() {
312 const [input, setInput] = useState("");
313 const { messages, sendMessage, isLoading, stop } = useChat({
314 connection: fetchServerSentEvents("/api/chat"),
315 threadId: "support-chat",
316 });
317
318 return (
319 <>
320 {messages.map((message) => (
321 <div key={message.id}>
322 {message.parts.map((part, index) =>
323 part.type === "text" ? <p key={index}>{part.content}</p> : null,
324 )}
325 </div>
326 ))}
327 <form
328 onSubmit={(event) => {
329 event.preventDefault();
330 if (input.trim() === "") {
331 return;
332 }
333 sendMessage(input);
334 setInput("");
335 }}
336 >
337 <input
338 value={input}
339 onInput={(event) => setInput(event.currentTarget.value)}
340 />
341 {isLoading ? (
342 <button type="button" onClick={stop}>
343 Stop
344 </button>
345 ) : (
346 <button type="submit">Send</button>
347 )}
348 </form>
349 </>
350 );
351}
352```
353
354See the [Preact API](../api/ai-preact).
355
356# Angular
357
358Call `injectChat` in a field initializer. State is a `Signal`. Read it by calling the function.
359
360```typescript ignore
361import { Component } from "@angular/core";
362import { FormsModule } from "@angular/forms";
363import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
364
365@Component({
366 selector: "app-chat",
367 standalone: true,
368 imports: [FormsModule],
369 template: `
370 <div>
371 @for (message of chat.messages(); track message.id) {
372 <div>
373 @for (part of message.parts; track $index) {
374 @if (part.type === "text") {
375 <p>{{ part.content }}</p>
376 }
377 }
378 </div>
379 }
380 <form (submit)="send($event)">
381 <input [(ngModel)]="draft" name="draft" [disabled]="chat.isLoading()" />
382 @if (chat.isLoading()) {
383 <button type="button" (click)="chat.stop()">Stop</button>
384 } @else {
385 <button type="submit" [disabled]="!draft.trim()">Send</button>
386 }
387 </form>
388 </div>
389 `,
390})
391export class ChatComponent {
392 chat = injectChat({
393 connection: fetchServerSentEvents("/api/chat"),
394 threadId: "support-chat",
395 });
396
397 draft = "";
398
399 send(event: Event) {
400 event.preventDefault();
401 const text = this.draft.trim();
402 if (text && !this.chat.isLoading()) {
403 void this.chat.sendMessage(text);
404 this.draft = "";
405 }
406 }
407}
408```
409
410Call `injectChat` in a field initializer or the constructor. A call in `ngOnInit` throws.
411
412`injectChat` subscribes to `DestroyRef`. In-flight requests stop when the component is destroyed.
413
414See the [Angular API](../api/ai-angular).
415
416# Octane
417
418Call `useChat` from `@tanstack/ai-octane`. Hold the composer text in `useState` from `octane`. Octane text controls fire `onInput`.
419
420`@tanstack/ai-octane` publishes uncompiled `.tsrx` source. Add `octane/compiler/vite` (or the rspack / rspeedy equivalent) to the app build.
421
422```tsx ignore
423import { useState } from "octane";
424import { useChat, fetchServerSentEvents } from "@tanstack/ai-octane";
425
426export function Chat() {
427 const [input, setInput] = useState("");
428 const { messages, sendMessage, isLoading, stop } = useChat({
429 connection: fetchServerSentEvents("/api/chat"),
430 threadId: "support-chat",
431 });
432
433 return (
434 <div>
435 {messages.map((message) => (
436 <div key={message.id}>
437 <p>
438 {message.parts
439 .filter((part) => part.type === "text")
440 .map((part) => part.content)
441 .join("")}
442 </p>
443 </div>
444 ))}
445 <form
446 onSubmit={(event) => {
447 event.preventDefault();
448 if (input.trim() === "") {
449 return;
450 }
451 void sendMessage(input);
452 setInput("");
453 }}
454 >
455 <input
456 value={input}
457 disabled={isLoading}
458 onInput={(event) => setInput(event.currentTarget.value)}
459 />
460 {isLoading ? (
461 <button type="button" onClick={stop}>
462 Stop
463 </button>
464 ) : (
465 <button type="submit">Send</button>
466 )}
467 </form>
468 </div>
469 );
470}
471```
472
473The hook calls `attach()` on mount. It calls `detach()` and `dispose()` on unmount.
474
475See the [Octane API](../api/ai-octane).
476
477# Remix
478
479Call `createChat(handle, options)` from `@tanstack/ai-remix` inside a `clientEntry` island. Put `connection` and `tools` in setup. They are not serializable `clientEntry` props.
480
481`@tanstack/ai-remix` publishes uncompiled source. Remix compiles JSX through `jsxImportSource` `remix/ui`. Bind the form with the Remix `on` mixin.
482
483```tsx ignore
484import { createChat, fetchServerSentEvents } from "@tanstack/ai-remix";
485import { clientEntry, on, type Handle } from "remix/ui";
486
487export const Chat = clientEntry(
488 import.meta.url,
489 function Chat(handle: Handle) {
490 const chat = createChat(handle, {
491 connection: fetchServerSentEvents("/api/chat"),
492 threadId: "support-chat",
493 });
494
495 return () => (
496 <div>
497 {chat.messages.map((message) => (
498 <div key={message.id}>
499 {message.parts.map((part, index) =>
500 part.type === "text" ? <p key={index}>{part.content}</p> : null,
501 )}
502 </div>
503 ))}
504 <form
505 mix={on("submit", (event) => {
506 event.preventDefault();
507 const form = event.currentTarget;
508 const text = String(
509 new FormData(form).get("message") ?? "",
510 ).trim();
511 if (text === "") {
512 return;
513 }
514 form.reset();
515 void chat.sendMessage(text);
516 })}
517 >
518 <input name="message" disabled={chat.isLoading} />
519 {chat.isLoading ? (
520 <button type="button" mix={on("click", () => chat.stop())}>
521 Stop
522 </button>
523 ) : (
524 <button type="submit">Send</button>
525 )}
526 </form>
527 </div>
528 );
529 },
530);
531```
532
533Read `chat.messages` and `chat.isLoading` in the render function so each paint sees the latest values.
534
535See the [Remix API](../api/ai-remix). For a typed headless chat UI, see [Remix Chat UI](../ui/remix).
536
537<!-- ::end:framework -->
538
539No framework? Use `ChatClient` from `@tanstack/ai-client`. See the [client API](../api/ai-client).
540
541## 4. Try it
542
543Start your app and send a message. The answer appears word by word while the model writes it. Click **Stop** to cancel a run.
544
545You now have a streaming chat.
546
547## How it works
548
5491. `sendMessage` posts the messages to `/api/chat`.
5502. `chatParamsFromRequest` reads the messages and the run ids from the request.
5513. `chat()` calls the model through the adapter and returns a stream of events.
5524. `toServerSentEventsResponse` sends those events back as Server-Sent Events.
5535. `fetchServerSentEvents` reads the events, and the hook adds each chunk to `messages`.
554
555Each message has `parts`. This page renders only the `text` parts. Tool calls and other content arrive as other part types.
556
557## Next
558
559Add one feature at a time:
560
561- [Tools](../tools/tools): let the model call your functions.
562- [Streaming](../chat/streaming): cancel, callbacks, and transports.
563- [Adapters](../adapters/openai): switch to another provider.
564
565Or build a full app in a tutorial, such as [Basic Chat](../tutorials/basic-chat) or [Generate Image](../tutorials/generate-image).
566
567## Advanced
568
569### Hosts
570
571The server route returns a Web `Response`. It works with any host that can return one:
572
573- TanStack Start
574- Next.js
575- SvelteKit
576- Hono
577- A Remix controller action
578
579If your server uses Node streams (Express), see [Quick Start: Server Only](./quick-start-server).
580
581### Bad request bodies
582
583If the request body is not valid, `chatParamsFromRequest` throws a `Response` with status 400.
584
585- TanStack Start, SolidStart, Remix, and React Router 7 return a thrown `Response` to the client for you.
586- Next.js Route Handlers, SvelteKit, Hono, and raw Node do not. Wrap the call in `try`/`catch` and return the caught `Response`.
587
588### Keys in the browser
589
590If you do not want a key on the server, users can paste their own provider key. See [Bring Your Own Key](../advanced/byok).