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

basic-chat.md

251 lines7.2 KB

1---
2title: Basic Chat
3id: basic-chat
4order: 1
5description: "Build a streaming React chat in a TanStack Start app. The user pastes an OpenRouter key in the tab, and useChat streams tokens from a server route."
6keywords:
7 - tanstack ai
8 - tutorial
9 - basic chat
10 - useChat
11 - byok
12 - openrouter
13 - tanstack start
14---
15​
16This tutorial builds a chat that streams tokens. The provider key stays in the browser for the demo.
17​
18The user pastes an OpenRouter key, and `useChat` sends it to a server route. It takes about 10 minutes.
19​
20This tutorial uses React and TanStack Start. For other frameworks, open [Quick Start](../getting-started/quick-start). To skip the setup, paste a key in the sandbox in step 5.
21​
22## 1. Create a Start app
23​
24```bash
25npx @tanstack/cli@latest create
26```
27​
28Pick React. For more options, see [Start getting started](https://tanstack.com/start/latest/docs/framework/react/quick-start).
29​
30Install the TanStack AI packages:
31​
32<!-- ::start:tabs variant="package-manager" mode="install" -->
33​
34react: @tanstack/ai @tanstack/ai-react @tanstack/ai-openrouter
35​
36<!-- ::end:tabs -->
37​
38Get an OpenRouter key from [openrouter.ai](https://openrouter.ai).
39​
40## 2. Keep the key in the tab
41​
42Create `src/lib/byok.ts`. `memoryStorage()` keeps the key in this tab only.
43​
44```typescript
45import { defineByok, memoryStorage } from '@tanstack/ai-react/byok'
46import { openrouterByok } from '@tanstack/ai-openrouter/byok'
47​
48export const byok = defineByok({
49 storage: memoryStorage(),
50 providers: [openrouterByok],
51})
52```
53​
54Create `src/components/open-router-key-form.tsx`. `byok.update` saves the key. `useByok` reads the status.
55​
56```tsx ignore
57import { useState } from 'react'
58import { openrouterByok } from '@tanstack/ai-openrouter/byok'
59import { useByok } from '@tanstack/ai-react'
60import { byok } from '@/lib/byok'
61​
62export function OpenRouterKeyForm() {
63 const snapshot = useByok(byok)
64 const [draft, setDraft] = useState('')
65 const [error, setError] = useState('')
66 const status = snapshot.status[openrouterByok.id]
67 const masked = status && 'masked' in status ? status.masked : undefined
68 const missingKey = snapshot.prompt?.reason === 'missing'
69​
70 return (
71 <form
72 onSubmit={(event) => {
73 event.preventDefault()
74 const next = draft.trim()
75 if (!next) return
76 setError('')
77 void byok
78 .update(openrouterByok.id, next)
79 .then(() => setDraft(''))
80 .catch((caught: unknown) =>
81 setError(
82 caught instanceof Error ? caught.message : 'Could not save key',
83 ),
84 )
85 }}
86 >
87 <input
88 type="password"
89 autoComplete="off"
90 placeholder={masked ? `Saved ${masked}` : 'Paste your OpenRouter key'}
91 value={draft}
92 onChange={(event) => setDraft(event.target.value)}
93 />
94 <button type="submit" disabled={!draft.trim()}>
95 Save key
96 </button>
97 {missingKey ? (
98 <p>Paste an OpenRouter key, then send again.</p>
99 ) : null}
100 {error ? <p>{error}</p> : null}
101 </form>
102 )
104```
105​
106For passkeys or other storage, open [Bring Your Own Key](../advanced/byok).
107​
108## 3. Add the chat page
109​
110Replace `src/routes/index.tsx` with this file. Pass `byok` to `useChat`. The hook then sends the key in an `x-byok-*` header.
111​
112```tsx ignore
113import { useState } from 'react'
114import { createFileRoute } from '@tanstack/react-router'
115import {
116 fetchServerSentEvents,
117 useChat,
118} from '@tanstack/ai-react'
119import { OpenRouterKeyForm } from '@/components/open-router-key-form'
120import { byok } from '@/lib/byok'
121​
122function ChatPage() {
123 const [input, setInput] = useState('')
124 const { messages, sendMessage, isLoading, error, stop } = useChat({
125 connection: fetchServerSentEvents('/api/chat'),
126 threadId: 'support-chat',
127 byok,
128 })
129​
130 const handleSendMessage = () => {
131 if (!input.trim()) return
132 sendMessage(input.trim())
133 setInput('')
134 }
135​
136 return (
137 <div>
138 <OpenRouterKeyForm />
139 {messages.map((message) => (
140 <div key={message.id}>
141 {message.parts.map((part, index) =>
142 part.type === 'text' ? <p key={index}>{part.content}</p> : null,
143 )}
144 </div>
145 ))}
146 {error ? <p>{error.message}</p> : null}
147 {isLoading ? (
148 <button type="button" onClick={stop}>
149 Stop
150 </button>
151 ) : null}
152 <textarea
153 value={input}
154 onChange={(event) => setInput(event.target.value)}
155 disabled={isLoading}
156 />
157 <button
158 type="button"
159 onClick={handleSendMessage}
160 disabled={!input.trim() || isLoading}
161 >
162 Send
163 </button>
164 </div>
165 )
167​
168export const Route = createFileRoute('/')({
169 component: ChatPage,
170})
171```
172​
173## 4. Add the server route
174​
175Create `src/routes/api.chat.ts`, next to `index.tsx`. Start maps this file name to the `/api/chat` path.
176​
177```typescript ignore
178import { createFileRoute } from '@tanstack/react-router'
179import {
180 chat,
181 chatParamsFromRequest,
182 toServerSentEventsResponse,
183} from '@tanstack/ai'
184import { createOpenRouterText } from '@tanstack/ai-openrouter'
185import { openrouterByok } from '@tanstack/ai-openrouter/byok'
186import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
187​
188export async function POST({ request }: { request: Request }) {
189 const params = await chatParamsFromRequest(request)
190 const apiKey = getByokKey(request, openrouterByok)
191 if (!apiKey) return byokMissing(openrouterByok)
192​
193 const stream = chat({
194 adapter: createOpenRouterText('openai/gpt-5.5', apiKey),
195 messages: params.messages,
196 threadId: params.threadId,
197 runId: params.runId,
198 })
199 return toServerSentEventsResponse(stream)
201​
202export const Route = createFileRoute('/api/chat')({
203 server: {
204 handlers: {
205 POST,
206 },
207 },
208})
209```
210​
211Import `openrouterByok` from `@tanstack/ai-openrouter/byok`, not from the main entry of the adapter.
212​
213## 5. Try it
214​
2151. Run the app.
2162. Paste an OpenRouter key.
2173. Send a message.
218​
219Tokens stream into the page. Click Stop to cancel the reply.
220​
221The same app is on the Examples tab at `/ai/latest/docs/framework/react/examples/basic-chat`.
222​
223<!-- ::client-example library=ai framework=react slug=basic-chat -->
224​
225You have a streaming chat, and the OpenRouter key never sits in a server env file.
226​
227## How it works
228​
229A chat has two sides:
230​
231- **The client** runs in the browser. It holds the key, shows the messages, and sends a POST to your route.
232- **The server route** reads the key, calls OpenRouter, and streams the tokens back.
233​
234On the client:
235​
236- `useChat` keeps `messages` up to date as tokens arrive.
237- If no key is saved, the hook does not send the POST. The form shows "Paste an OpenRouter key, then send again."
238​
239On the server:
240​
241- `getByokKey` reads the `x-byok-openrouter` header first. If the header is empty, it reads `OPENROUTER_API_KEY` from the environment.
242- If both are empty, `byokMissing` returns HTTP 401.
243- `toServerSentEventsResponse` turns the `chat()` stream into a Server-Sent Events response.
244​
245The full example is on GitHub: [TanStack/ai `examples/react/basic-chat`](https://github.com/TanStack/ai/tree/main/examples/react/basic-chat).
246​
247Next, pick one:
248​
249- A headless chat UI: [A chat box with no tools](../ui/recipes/basic-chat).
250- An image from a prompt: [Generate Image](./generate-image).
251- A table that fills as JSON streams: [Streaming Structured Table](./streaming-structured-table).