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

generate-image.md

342 lines10.5 KB

1---
2title: Generate Image
3id: generate-image
4order: 2
5description: "Build a React prompt box that returns an image in a TanStack Start app. The user pastes an OpenRouter key in the tab, and useGenerateImage calls a server route that runs generateImage."
6keywords:
7 - tanstack ai
8 - tutorial
9 - generate image
10 - useGenerateImage
11 - generateImage
12 - byok
13 - openrouter
14 - tanstack start
15---
16​
17This tutorial builds a prompt box that returns an image. The provider key stays in the browser for the demo.
18​
19The user pastes an OpenRouter key. `useGenerateImage` sends the prompt to a server route, and the route runs `generateImage`. It takes about 10 minutes.
20​
21This tutorial uses React and TanStack Start. For other frameworks, open [Quick Start](../getting-started/quick-start). For sizes and other providers, open [Image Generation](../media/image-generation). To skip the setup, paste a key in the sandbox in step 5.
22​
23## 1. Create a Start app
24​
25```bash
26npx @tanstack/cli@latest create
27```
28​
29Pick React. For more options, see [Start getting started](https://tanstack.com/start/latest/docs/framework/react/quick-start).
30​
31Install the TanStack AI packages:
32​
33<!-- ::start:tabs variant="package-manager" mode="install" -->
34​
35react: @tanstack/ai @tanstack/ai-react @tanstack/ai-openrouter
36​
37<!-- ::end:tabs -->
38​
39Get an OpenRouter key from [openrouter.ai](https://openrouter.ai).
40​
41## 2. Keep the key in the tab
42​
43Create `src/lib/byok.ts`. `memoryStorage()` keeps the key in this tab only.
44​
45```typescript
46import { defineByok, memoryStorage } from '@tanstack/ai-react/byok'
47import { openrouterByok } from '@tanstack/ai-openrouter/byok'
48​
49export const byok = defineByok({
50 storage: memoryStorage(),
51 providers: [openrouterByok],
52})
53```
54​
55Create `src/components/open-router-key-form.tsx`. `byok.update` saves the key. `useByok` reads the status.
56​
57```tsx ignore
58import { useState } from 'react'
59import { openrouterByok } from '@tanstack/ai-openrouter/byok'
60import { useByok } from '@tanstack/ai-react'
61import { byok } from '@/lib/byok'
62​
63export function OpenRouterKeyForm() {
64 const snapshot = useByok(byok)
65 const [draft, setDraft] = useState('')
66 const [error, setError] = useState('')
67 const status = snapshot.status[openrouterByok.id]
68 const masked = status && 'masked' in status ? status.masked : undefined
69 const missingKey = snapshot.prompt?.reason === 'missing'
70​
71 return (
72 <form
73 onSubmit={(event) => {
74 event.preventDefault()
75 const next = draft.trim()
76 if (!next) return
77 setError('')
78 void byok
79 .update(openrouterByok.id, next)
80 .then(() => setDraft(''))
81 .catch((caught: unknown) =>
82 setError(
83 caught instanceof Error ? caught.message : 'Could not save key',
84 ),
85 )
86 }}
87 >
88 <input
89 type="password"
90 autoComplete="off"
91 placeholder={masked ? `Saved ${masked}` : 'Paste your OpenRouter key'}
92 value={draft}
93 onChange={(event) => setDraft(event.target.value)}
94 />
95 <button type="submit" disabled={!draft.trim()}>
96 Save key
97 </button>
98 {missingKey ? (
99 <p>Paste an OpenRouter key, then generate again.</p>
100 ) : null}
101 {error ? <p>{error}</p> : null}
102 </form>
103 )
105```
106​
107For passkeys or other storage, open [Bring Your Own Key](../advanced/byok).
108​
109## 3. Add the prompt page
110​
111Replace `src/routes/index.tsx` with this file. Pass `byok` to `useGenerateImage`. The hook then sends the key in an `x-byok-*` header.
112​
113```tsx ignore
114import { useState } from 'react'
115import { createFileRoute } from '@tanstack/react-router'
116import { fetchServerSentEvents, useGenerateImage } from '@tanstack/ai-react'
117import { OpenRouterKeyForm } from '@/components/open-router-key-form'
118import { byok } from '@/lib/byok'
119​
120// OpenRouter returns a public URL or raw base64. <img src> accepts both.
121function imageSrc(image: { url?: string; b64Json?: string }) {
122 if (image.url) return image.url
123 if (image.b64Json) return `data:image/png;base64,${image.b64Json}`
124 return undefined
126​
127function ImagePage() {
128 const [prompt, setPrompt] = useState('')
129 // POST { prompt } to /api/generate/image over SSE.
130 // byok sends the OpenRouter key as x-byok-openrouter.
131 // When the stream ends, result.images holds the picture.
132 const { generate, result, isLoading, error, stop } = useGenerateImage({
133 connection: fetchServerSentEvents('/api/generate/image'),
134 threadId: 'image-studio',
135 byok,
136 })
137​
138 const handleGenerate = () => {
139 const next = prompt.trim()
140 if (!next) return
141 void generate({ prompt: next })
142 }
143​
144 return (
145 <div>
146 <OpenRouterKeyForm />
147 {result?.images[0] ? (
148 <img
149 src={imageSrc(result.images[0])}
150 alt={prompt.trim() || 'Generated image'}
151 />
152 ) : null}
153 {error ? <p>{error.message}</p> : null}
154 {isLoading ? (
155 <button type="button" onClick={stop}>
156 Stop
157 </button>
158 ) : null}
159 <textarea
160 value={prompt}
161 onChange={(event) => setPrompt(event.target.value)}
162 disabled={isLoading}
163 />
164 <button
165 type="button"
166 onClick={handleGenerate}
167 disabled={!prompt.trim() || isLoading}
168 >
169 Generate
170 </button>
171 </div>
172 )
174​
175export const Route = createFileRoute('/')({
176 component: ImagePage,
177})
178```
179​
180## 4. Add the server route
181​
182Create `src/routes/api.generate.image.ts`, next to `index.tsx`. Start maps this file name to the `/api/generate/image` path.
183​
184```typescript ignore
185import { createFileRoute } from '@tanstack/react-router'
186import {
187 generateImage,
188 generationParamsFromRequest,
189 toServerSentEventsResponse,
190} from '@tanstack/ai'
191import { createOpenRouterImage } from '@tanstack/ai-openrouter'
192import { openrouterByok } from '@tanstack/ai-openrouter/byok'
193import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
194​
195export async function POST({ request }: { request: Request }) {
196 // Unwrap the prompt the hook POSTed. Then read the OpenRouter key.
197 const { input, threadId, runId } = await generationParamsFromRequest(
198 'image',
199 request,
200 )
201 const apiKey = getByokKey(request, openrouterByok)
202 if (!apiKey) return byokMissing(openrouterByok)
203 if (typeof input.prompt !== 'string') {
204 return new Response('This route accepts a text prompt only.', {
205 status: 400,
206 })
207 }
208 // The hook always sends its threadId. A bare body has none.
209​
210 // Call OpenRouter. stream: true so the hook can listen on SSE.
211 // The hook stores the finished picture on result.images.
212 const stream = generateImage({
213 adapter: createOpenRouterImage('google/gemini-nano-banana-2.1', apiKey),
214 prompt: input.prompt,
215 stream: true,
216 threadId,
217 runId,
218 })
219 return toServerSentEventsResponse(stream)
221​
222export const Route = createFileRoute('/api/generate/image')({
223 server: {
224 handlers: {
225 POST,
226 },
227 },
228})
229```
230​
231Import `openrouterByok` from `@tanstack/ai-openrouter/byok`, not from the main entry of the adapter.
232​
233## 5. Try it
234​
2351. Run the app.
2362. Paste an OpenRouter key.
2373. Type a prompt and click Generate.
238​
239The image shows on the page.
240​
241The same app is on the Examples tab at `/ai/latest/docs/framework/react/examples/generate-image`.
242​
243<!-- ::client-example library=ai framework=react slug=generate-image -->
244​
245You have an image from a prompt, and the OpenRouter key never sits in a server env file.
246​
247## How it works
248​
249The generation has two sides:
250​
251- **The client** runs in the browser. It holds the key, shows the prompt box, and sends a POST to your route.
252- **The server route** reads the key, calls OpenRouter, and streams the image back.
253​
254On the client:
255​
256- `generate({ prompt })` starts the run.
257- `result.images` holds the image when it arrives.
258- If no key is saved, the hook does not send the POST. The form shows "Paste an OpenRouter key, then generate again."
259​
260On the server:
261​
262- `generationParamsFromRequest` reads the prompt from the POST body.
263- `getByokKey` reads the `x-byok-openrouter` header first. If the header is empty, it reads `OPENROUTER_API_KEY` from the environment. If both are empty, `byokMissing` returns HTTP 401.
264- `stream: true` makes `generateImage` return a stream, so `toServerSentEventsResponse` can send it to the hook.
265- The route accepts a text prompt only. OpenRouter returns one image for each request.
266​
267The full example is on GitHub: [TanStack/ai `examples/react/generate-image`](https://github.com/TanStack/ai/tree/main/examples/react/generate-image).
268​
269For sizes, image-to-image, and other providers, open [Image Generation](../media/image-generation).
270​
271## Advanced
272​
273### Transform `result` with `onResult`
274​
275`result` is the full `ImageGenerationResult`, so the page still picks a URL or base64 for `<img>`. Pass `onResult` to do that work in the hook. Return a `src` string, and the hook stores that string on `result`.
276​
277The server route does not change. Only the page changes:
278​
279```tsx ignore
280import { useState } from 'react'
281import { createFileRoute } from '@tanstack/react-router'
282import { fetchServerSentEvents, useGenerateImage } from '@tanstack/ai-react'
283import { OpenRouterKeyForm } from '@/components/open-router-key-form'
284import { byok } from '@/lib/byok'
285​
286function ImagePage() {
287 const [prompt, setPrompt] = useState('')
288 // POST { prompt } to /api/generate/image over SSE.
289 // onResult runs when the image arrives. The return value becomes `result`.
290 const { generate, result, isLoading, error, stop } = useGenerateImage({
291 connection: fetchServerSentEvents('/api/generate/image'),
292 threadId: 'image-studio',
293 byok,
294 onResult: (raw) => {
295 const image = raw.images[0]
296 if (image?.url) return image.url
297 if (image?.b64Json) return `data:image/png;base64,${image.b64Json}`
298 return null
299 },
300 })
301​
302 const handleGenerate = () => {
303 const next = prompt.trim()
304 if (!next) return
305 void generate({ prompt: next })
306 }
307​
308 return (
309 <div>
310 <OpenRouterKeyForm />
311 {result ? (
312 <img src={result} alt={prompt.trim() || 'Generated image'} />
313 ) : null}
314 {error ? <p>{error.message}</p> : null}
315 {isLoading ? (
316 <button type="button" onClick={stop}>
317 Stop
318 </button>
319 ) : null}
320 <textarea
321 value={prompt}
322 onChange={(event) => setPrompt(event.target.value)}
323 disabled={isLoading}
324 />
325 <button
326 type="button"
327 onClick={handleGenerate}
328 disabled={!prompt.trim() || isLoading}
329 >
330 Generate
331 </button>
332 </div>
333 )
335​
336export const Route = createFileRoute('/')({
337 component: ImagePage,
338})
339```
340​
341- A returned string replaces `result`.
342- A `null` return keeps the previous `result`.