Open History to see the last commit
1---
2title: Keep Generated Files (Advanced)
3id: keep-generated-files
4---
5
6Copy generated media into your store before the provider URL expires. A Sora clip, an image batch, or a long audio track otherwise stops loading.
7
8To keep the output, save the generated bytes to your own storage and serve them from your own origin.
9
10## Quick setup
11
12This adds to [Generation persistence](./generation-persistence). Set that up first.
13
14### 1. Give the backend byte storage
15
16Byte storage needs two stores, and you must provide both:
17
18- `artifacts`: the metadata of each file.
19- `blobs`: the bytes.
20
21`memoryPersistence()` has both, plus `generationRuns`. Any backend that implements `ArtifactStore` and `BlobStore` works the same way. See [Build a generation adapter](./build-your-own-generation-adapter).
22
23### 2. Stamp a durable URL in the generation route
24
25Pass `artifactUrl` to `withGenerationPersistence`. It returns the URL of the serve route from step 3:
26
27```ts group=generation-bytes
28// routes/api.generate.image.ts, runs the generation.
29import {
30 generateImage,
31 generationParamsFromRequest,
32 toServerSentEventsResponse,
33} from '@tanstack/ai'
34import { openaiImage } from '@tanstack/ai-openai'
35import {
36 memoryPersistence,
37 retrieveArtifact,
38 retrieveBlob,
39 withGenerationPersistence,
40} from '@tanstack/ai-persistence'
41
42const persistence = memoryPersistence()
43
44export async function POST(request: Request) {
45 const { input, threadId } = await generationParamsFromRequest(
46 'image',
47 request,
48 )
49
50 if (typeof input.prompt !== 'string') {
51 throw new Error('This endpoint accepts text image prompts only.')
52 }
53
54
55 const stream = generateImage({
56 adapter: openaiImage('gpt-image-2.5-flare'),
57 prompt: input.prompt,
58 threadId,
59 stream: true,
60 middleware: [
61 withGenerationPersistence(persistence, {
62 // Stamp the serve URL (the artifact route below) on every stored
63 // artifact ref. The live result and the restored result then both
64 // load from your own origin, not from the expiring provider link.
65 artifactUrl: (ref) =>
66 `/api/generate/image/artifact?id=${ref.artifactId}`,
67 }),
68 ],
69 })
70
71 return toServerSentEventsResponse(stream)
72}
73```
74
75### 3. Add a route that serves the bytes
76
77Use a **separate** route. The `GET` on the generation route already answers hydration and resume for [Generation persistence](./generation-persistence):
78
79```ts group=generation-bytes
80// routes/api.generate.image.artifact.ts, serves stored bytes by id.
81//
82// Security: the id comes from the caller, so this route MUST authorize before
83// it serves. `ArtifactRecord` has the `threadId` and `runId` that the file was
84// generated under. Compare them with an identity from the server session,
85// never from the query string. Without this check, any caller who learns or
86// guesses an artifact id can read the media of another user.
87export async function GET(request: Request) {
88 const artifactId = new URL(request.url).searchParams.get('id')
89 if (!artifactId) return new Response('missing id', { status: 400 })
90
91 const artifact = await retrieveArtifact(persistence, artifactId)
92 if (!artifact) return new Response('not found', { status: 404 })
93
94 // Replace with your session and ownership check, for example:
95 // const user = await auth(request)
96 // const owned = user != null && (await db.threadOwnedBy(user.id, artifact.threadId))
97 const owned = true
98 void request
99 // 404, not 403. A separate "exists but forbidden" answer confirms valid ids.
100 if (!owned) return new Response('not found', { status: 404 })
101
102 const blob = await retrieveBlob(persistence, artifact)
103 if (!blob) return new Response('not found', { status: 404 })
104
105 return new Response(blob.body ?? (await blob.arrayBuffer()), {
106 headers: {
107 'content-type': artifact.mimeType,
108 'content-length': String(artifact.size),
109 },
110 })
111}
112```
113
114### 4. Use the result in the client
115
116You do not change the client. `result.images[i].url` already points at your route. Generate an image, reload the page, and the image still loads after the provider link expires.
117
118## How it works
119
120With both stores present, `withGenerationPersistence` does this for each generated file:
121
1221. It writes the bytes to the blob store, under the key `artifacts/<runId>/<artifactId>` by default.
1232. It records an `ArtifactRecord`.
1243. It attaches durable references to the result and to the run record.
125
126Without the two stores, only the run record is kept.
127
128`artifactUrl` makes the stored bytes reachable from the client. For each stored ref, it returns the URL on your origin that serves the bytes. Then `withGenerationPersistence` does two things with it:
129
130- It stamps the URL on the ref, as `ref.url`.
131- It rewrites the media field of the live result to the same URL: `result.images[i].url` for images, `result.url` for a video, and `result.audio.url` for audio.
132
133The durable refs travel on `result.artifacts`. On mount, the generation hook rebuilds `result` from these refs and sets each media field to its `ref.url`. So the restored result shows the same media as the live run. `result.artifacts` is the full artifact surface on the hook. There are no other top-level artifact fields, live or restored.
134
135`memoryPersistence` keeps everything in process memory. That is correct for development and tests. For production, point `generationRuns`, `artifacts`, and `blobs` at a durable backend.
136
137## Advanced
138
139### Serve video: honor `Range`
140
141The route above is enough for images, but not for video. Seeking in a `<video>` uses HTTP range requests. If a source answers every `Range` with the whole file, the user cannot seek. Safari does not play it at all, and other browsers download the full clip before it starts.
142
143Pass `range` to `retrieveBlob` and answer with `206`:
144
145```ts group=generation-bytes
146import { parseRangeHeader } from '@tanstack/ai-persistence'
147import type { ArtifactRecord } from '@tanstack/ai-persistence'
148
149// The same route, with seek support. `parseRangeHeader` resolves the header
150// against the size on the record. It handles suffix ranges (`bytes=-500` is the
151// LAST 500 bytes) and the unsatisfiable case. `blob.range` then reports the
152// slice that was served, and `artifact.size` the whole file: the two numbers
153// that `Content-Range` needs.
154export async function serveArtifactBytes(
155 request: Request,
156 artifact: ArtifactRecord,
157) {
158 const range = parseRangeHeader(request.headers.get('range'), artifact.size)
159 if (range === 'unsatisfiable') {
160 return new Response('range not satisfiable', {
161 status: 416,
162 headers: { 'content-range': `bytes */${artifact.size}` },
163 })
164 }
165
166 const blob = await retrieveBlob(
167 persistence,
168 artifact,
169 range ? { range } : undefined,
170 )
171 if (!blob) return new Response('not found', { status: 404 })
172
173 const body = blob.body ?? (await blob.arrayBuffer())
174 // `accept-ranges` goes on every response, also the whole-file one. It tells
175 // the player that it can seek.
176 const headers = {
177 'content-type': artifact.mimeType,
178 'accept-ranges': 'bytes',
179 }
180 if (!blob.range) {
181 return new Response(body, {
182 headers: { ...headers, 'content-length': String(artifact.size) },
183 })
184 }
185 const { offset, length } = blob.range
186 return new Response(body, {
187 status: 206,
188 headers: {
189 ...headers,
190 'content-length': String(length),
191 'content-range': `bytes ${offset}-${offset + length - 1}/${artifact.size}`,
192 },
193 })
194}
195```
196
197The client needs nothing special. When the route answers ranges, the browser does the rest:
198
199```tsx
200import type { PersistedArtifactRef } from '@tanstack/ai'
201
202export function GeneratedVideo({ artifact }: { artifact: PersistedArtifactRef }) {
203 // `artifact.url` is the URL on your origin that `artifactUrl` stamped on the ref.
204 return <video src={artifact.url} controls preload="metadata" />
205}
206```
207
208With `preload="metadata"`, the player fetches the header bytes with a range request. It shows the duration and the seek bar without a download of the full clip. The store must support ranged reads for this to work. The [conformance testkit](./store-reference#blobstore) checks it.
209
210### Choose what gets captured
211
212Two options of `withGenerationPersistence` control the capture:
213
214- `extractArtifacts`: return your own descriptors. A custom `extractArtifacts` replaces the built-in rule.
215- `nameArtifact`: give each file a name.
216
217If you use a video provider with [no public URL](../media/video-generation#videos-with-no-public-url) and a custom `extractArtifacts`, return a descriptor with `bytes: result.body` for the video. If you do not, the stream is not stored, and `url` is a base64 `data:` URL.
218
219### Choose where the bytes land
220
221By default, the bytes go under `artifacts/<runId>/<artifactId>`. Pass `storageKey` to use your own folder structure. This helps when your app shares the bucket, or when you want media grouped by the thing it belongs to, not by the run:
222
223```ts group=generation-bytes
224const storageKeyOptions = withGenerationPersistence(persistence, {
225 storageKey: ({ runId, artifactId, role, name }) =>
226 `products/${role}/${runId}-${artifactId}-${name}`,
227})
228```
229
230- **The resolved key is saved on the artifact.** A custom path cannot be computed again from the record. So it is stored as `ArtifactRecord.blobKey`, and reads use it. Every record must have `blobKey`. A record without it does not load.
231- **A key that is not unique overwrites.** Include `artifactId`, or another unique value, unless you want the overwrite.
232- **This is server-side only.** A key from the browser can cause path traversal and writes into the data of another tenant.
233
234### Prompt media referenced by URL
235
236The middleware stores the **generated output**. When a provider returns a link that expires, the middleware downloads it and keeps the bytes.
237
238Prompt media is different. It depends on how you sent it:
239
240- **base64** (`source: { type: 'data' }`): stored with the output, because the bytes are already on the server.
241- **a URL** (`source: { type: 'url' }`): **not fetched**, and no artifact is recorded.
242
243The middleware leaves a caller URL alone for two reasons:
244
245- A server-side download lets anyone name an address that your server can reach, for example a cloud metadata endpoint or a `localhost` admin service. The caller can then read the response through the artifact `GET` route.
246- The copy is not necessary. The caller already had the media.
247
248If you need a durable copy of caller media (for example a "paste an image URL" input), opt in with `allowInputUrl`. It is a predicate, not a flag, so you must write the check:
249
250```ts group=generation-bytes
251const inputUrlOptions = withGenerationPersistence(persistence, {
252 allowInputUrl: ({ url }) => url.hostname.endsWith('.cdn.example.com'),
253})
254```
255
256Every artifact fetch, input or output, has three limits:
257
258- The scheme must be `http:` or `https:`.
259- The fetch stops after `artifactFetchTimeoutMs` (default 30s).
260- The body is capped at `maxArtifactBytes` (default 1 GiB) while it drains. Pass `false` for no cap. See [Nothing is buffered](#nothing-is-buffered).
261
262Input fetches add two more limits:
263
264- A block on loopback, private, and link-local hosts.
265- No redirects, so a `302` cannot go to an address that the check did not see.
266
267These limits are a backstop, not the main control. A hostname that *resolves* to a private address still passes a literal-IP check. Keep `allowInputUrl` narrow. For stronger isolation, inject `artifactFetch` to send downloads through an egress-restricted proxy. That proxy can check the address that the connection actually reached.
268
269### Nothing is buffered
270
271The middleware **streams** a provider URL into the blob store. It never holds the artifact in memory, and it counts `size` on the record as the bytes drain. A 2 GB video costs a streaming store (R2, S3, a filesystem) the same memory as a 2 KB icon.
272
273`memoryPersistence` is the exception, because it keeps the bytes in process by design. It is a store for development and tests, not for production.
274
275So `maxArtifactBytes` limits **transfer**, not memory. It puts a ceiling on what a runaway or hostile origin can make you download and store. `content-length` is only a claim: an origin can declare 1 KB and send data without end. That is the only reason for the default.
276
277#### A provider stream is stored the same way
278
279Some video providers return the finished video as a stream, with no URL to fetch. See [Videos with no public URL](../media/video-generation#videos-with-no-public-url). The middleware passes that stream to `BlobStore.put` as it is, so memory stays flat here too.
280
281There are two differences from a fetched URL:
282
283- **No declared length.** The stream has no `content-length`, and the middleware sends no `BlobPutOptions.expectedLength`. Your store must accept a stream of unknown length. On R2, that means a multipart upload.
284- **No size cap.** `maxArtifactBytes` applies to URL fetches only.
285
286#### The body reaches your store untouched when possible
287
288To enforce the cap during the drain, the middleware wraps the body in a `TransformStream` that counts. The readable side of a transform has **no declared length**, and the workerd `R2Bucket.put` needs that length for a single-shot upload. So the middleware adds the wrapper only where it is necessary:
289
290| The response | What your store gets |
291| --- | --- |
292| Declares a `content-length`, no `content-encoding` | The `fetch` body **untouched**, with its length |
293| Chunked, no declared length | The counting wrapper |
294| `content-encoding: gzip` (the declared length is compressed) | The counting wrapper |
295
296In the first row, the counter is not necessary. The declared length was already checked against the cap, and HTTP framing holds the origin to it. That is the common case for a provider CDN. So on Cloudflare, the default configuration streams straight through:
297
298```ts ignore
299// Inside your BlobStore.put on workerd: nothing buffered, no multipart, no
300// hint needed. (`R2Bucket` comes from @cloudflare/workers-types.)
301const putStraightToR2 = (bucket: R2Bucket, key: string, body: BlobBody) =>
302 bucket.put(key, body)
303```
304
305The other two rows need the counter:
306
307- A chunked reply declares no length.
308- A compressed reply can decode to much more than it declared (a decompression bomb).
309
310For those rows, `BlobPutOptions.expectedLength` is also absent. A store that needs a length then uses a multipart upload. That upload buffers one 8 MiB part at a time, so memory stays flat for any artifact size. The `ai-persistence/build-cloudflare-artifact-store` skill has that recipe.
311
312To remove the ceiling (no counter on any response, no limit on what an origin can stream into your bucket), pass `false`:
313
314```ts group=generation-bytes
315const uncappedOptions = withGenerationPersistence(persistence, {
316 maxArtifactBytes: false,
317})
318```
319
320Use this when you trust the origins that you fetch from. The limits of your storage backend still apply. For example, R2 caps a single-shot upload at 5 GiB and a multipart upload at 10,000 parts.
321
322Keep the cap when `allowInputUrl` lets callers name the URL. Then you do not control the origin.