Open History to see the last commit
1---
2title: Basic Chat
3id: basic-chat
4order: 1
5description: "Create a TanStack Start app, then add a streaming React chat. BYOK holds the OpenRouter key in the tab. useChat talks to a server route that streams tokens."
6keywords:
7 - tanstack ai
8 - tutorial
9 - basic chat
10 - useChat
11 - byok
12 - openrouter
13 - tanstack start
14---
15
16Create a TanStack Start app. Then add a streaming chat.
17
18This tutorial is React + Start. For other frameworks, open [Quick Start](../getting-started/quick-start).
19
20You can skip the scaffold and paste a key in the sandbox at the end of this page.
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
30Then install 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## Client and server
41
42A chat has two sides.
43
44The **client** runs in the browser. It holds the key, draws messages, and POSTs to your route.
45
46The **server** route reads that key, calls OpenRouter, and streams tokens back.
47
48The next steps build the client. Then they add the route.
49
50## 2. Set up BYOK on the client
51
52Create `src/lib/byok.ts`. `memoryStorage()` keeps the key in this tab.
53
54```typescript
55import { defineByok, memoryStorage } from '@tanstack/ai-react/byok'
56import { openrouterByok } from '@tanstack/ai-openrouter/byok'
57
58export const byok = defineByok({
59 storage: memoryStorage(),
60 providers: [openrouterByok],
61})
62```
63
64Create `src/components/open-router-key-form.tsx`. Export `OpenRouterKeyForm` from that file. `byok.update` saves the key. `useByok` reads the status.
65
66```tsx ignore
67import { useState } from 'react'
68import { openrouterByok } from '@tanstack/ai-openrouter/byok'
69import { useByok } from '@tanstack/ai-react'
70import { byok } from '@/lib/byok'
71
72export function OpenRouterKeyForm() {
73 const snapshot = useByok(byok)
74 const [draft, setDraft] = useState('')
75 const [error, setError] = useState('')
76 const status = snapshot.status[openrouterByok.id]
77 const masked = status && 'masked' in status ? status.masked : undefined
78 const missingKey = snapshot.prompt?.reason === 'missing'
79
80 return (
81 <form
82 onSubmit={(event) => {
83 event.preventDefault()
84 const next = draft.trim()
85 if (!next) return
86 setError('')
87 void byok
88 .update(openrouterByok.id, next)
89 .then(() => setDraft(''))
90 .catch((caught: unknown) =>
91 setError(
92 caught instanceof Error ? caught.message : 'Could not save key',
93 ),
94 )
95 }}
96 >
97 <input
98 type="password"
99 autoComplete="off"
100 placeholder={masked ? `Saved ${masked}` : 'Paste your OpenRouter key'}
101 value={draft}
102 onChange={(event) => setDraft(event.target.value)}
103 />
104 <button type="submit" disabled={!draft.trim()}>
105 Save key
106 </button>
107 {missingKey ? (
108 <p>Paste an OpenRouter key, then send again.</p>
109 ) : null}
110 {error ? <p>{error}</p> : null}
111 </form>
112 )
113}
114```
115
116If you want passkeys, open [Bring Your Own Key](../advanced/byok).
117
118## 3. Hook up `useChat`
119
120Open `src/routes/index.tsx`. Import `OpenRouterKeyForm` from `@/components/open-router-key-form`. Pass `byok` to `useChat`. The hook sends the key in an `x-byok-*` header.
121
122```tsx ignore
123import { useState } from 'react'
124import { createFileRoute } from '@tanstack/react-router'
125import {
126 fetchServerSentEvents,
127 useChat,
128} from '@tanstack/ai-react'
129import { OpenRouterKeyForm } from '@/components/open-router-key-form'
130import { byok } from '@/lib/byok'
131
132function ChatPage() {
133 const [input, setInput] = useState('')
134 const { messages, sendMessage, isLoading, error, stop } = useChat({
135 connection: fetchServerSentEvents('/api/chat'),
136 byok,
137 })
138
139 const handleSendMessage = () => {
140 if (!input.trim()) return
141 sendMessage(input.trim())
142 setInput('')
143 }
144
145 return (
146 <div>
147 <OpenRouterKeyForm />
148 {messages.map((message) => (
149 <div key={message.id}>
150 {message.parts.map((part, index) =>
151 part.type === 'text' ? <p key={index}>{part.content}</p> : null,
152 )}
153 </div>
154 ))}
155 {error ? <p>{error.message}</p> : null}
156 {isLoading ? (
157 <button type="button" onClick={stop}>
158 Stop
159 </button>
160 ) : null}
161 <textarea
162 value={input}
163 onChange={(event) => setInput(event.target.value)}
164 disabled={isLoading}
165 />
166 <button
167 type="button"
168 onClick={handleSendMessage}
169 disabled={!input.trim() || isLoading}
170 >
171 Send
172 </button>
173 </div>
174 )
175}
176
177export const Route = createFileRoute('/')({
178 component: ChatPage,
179})
180```
181
182`messages` updates as tokens arrive. Click Stop to cancel.
183
184A send with no key does not POST. The form shows "Paste an OpenRouter key, then send again."
185
186## 4. Add the server route
187
188Create `src/routes/api.chat.ts` in the `src/routes` folder, next to `index.tsx`. Start maps that file name to the `/api/chat` path. Do this in two steps.
189
190### Read the key
191
192`getByokKey` reads the `x-byok-openrouter` header, then `OPENROUTER_API_KEY` in the environment. If both are empty, `byokMissing` returns HTTP 401.
193
194```typescript ignore
195import { createFileRoute } from '@tanstack/react-router'
196import { chatParamsFromRequest } from '@tanstack/ai'
197import { openrouterByok } from '@tanstack/ai-openrouter/byok'
198import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
199
200export async function POST({ request }: { request: Request }) {
201 const params = await chatParamsFromRequest(request)
202 const apiKey = getByokKey(request, openrouterByok)
203 if (!apiKey) return byokMissing(openrouterByok)
204
205 return new Response('ok')
206}
207
208export const Route = createFileRoute('/api/chat')({
209 server: {
210 handlers: {
211 POST,
212 },
213 },
214})
215```
216
217This is a stub. The next step replaces the `ok` body.
218
219Import `openrouterByok` from `@tanstack/ai-openrouter/byok`, not from the adapter main entry.
220
221### Call `chat` and return the stream
222
223Replace the `ok` response. Pass the key into `createOpenRouterText`. Wrap `chat()` with `toServerSentEventsResponse`.
224
225```typescript ignore
226import { createFileRoute } from '@tanstack/react-router'
227import {
228 chat,
229 chatParamsFromRequest,
230 toServerSentEventsResponse,
231} from '@tanstack/ai'
232import { createOpenRouterText } from '@tanstack/ai-openrouter'
233import { openrouterByok } from '@tanstack/ai-openrouter/byok'
234import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
235
236export async function POST({ request }: { request: Request }) {
237 const params = await chatParamsFromRequest(request)
238 const apiKey = getByokKey(request, openrouterByok)
239 if (!apiKey) return byokMissing(openrouterByok)
240
241 const stream = chat({
242 adapter: createOpenRouterText('openai/gpt-5.5', apiKey),
243 messages: params.messages,
244 threadId: params.threadId,
245 runId: params.runId,
246 })
247 return toServerSentEventsResponse(stream)
248}
249
250export const Route = createFileRoute('/api/chat')({
251 server: {
252 handlers: {
253 POST,
254 },
255 },
256})
257```
258
259## 5. Try it
260
261Run the app. Paste an OpenRouter key. Send a message. Tokens stream into the UI.
262
263The same app is on the Examples tab at `/ai/latest/docs/framework/react/examples/basic-chat`.
264
265<!-- ::client-example library=ai framework=react slug=basic-chat -->
266
267You have a streaming chat. The OpenRouter key never sits in a server env file.
268
269The full example is on GitHub: [TanStack/ai `examples/react/basic-chat`](https://github.com/TanStack/ai/tree/main/examples/react/basic-chat).
270
271For a headless chat UI, open [A chat box with no tools](../ui/recipes/basic-chat).
272
273For an image from a prompt, open [Generate Image](./generate-image).
274
275For a table that fills as JSON streams, open [Streaming Structured Table](./streaming-structured-table).