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

client-persistence.md

356 lines13.9 KB

1---
2title: Client Persistence
3id: client-persistence
4---
5​
6Client persistence writes `useChat` messages to storage in the browser. A reload keeps the conversation and a reply that was still streaming.
7​
8On reload, the `persistence` option also brings back a pending approval.
9​
10## Quick setup
11​
12Pick who owns the history. Then copy that path.
13​
14### The browser owns the chat
15​
16Use this for a single-page app, an offline-first app, or any app with no server store. Pass a storage adapter and a stable `threadId`:
17​
18```tsx
19import {
20 fetchServerSentEvents,
21 localStoragePersistence,
22 useChat,
23} from '@tanstack/ai-react'
24​
25export function Chat() {
26 const { messages, sendMessage } = useChat({
27 threadId: 'support-chat',
28 connection: fetchServerSentEvents('/api/chat'),
29 persistence: localStoragePersistence(),
30 })
31 return (
32 <div>
33 {messages.map((message) => (
34 <div key={message.id}>{message.role}</div>
35 ))}
36 <button type="button" onClick={() => void sendMessage('hi')}>
37 Send
38 </button>
39 </div>
40 )
42```
43​
44`localStoragePersistence()` needs no type argument and no codec. It uses the chat record shape and a JSON codec by default.
45​
46Send a message and reload. The conversation is there, with no network call.
47​
48### The server owns the chat
49​
50Use this for large transcripts, for the same chat on more than one device, or to keep message content out of the browser. You need [Chat persistence](./chat-persistence) on the server first.
51​
521. Set `persistence: true` in the client:
53​
54 ```tsx
55 import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
56​
57 export function Chat({ threadId }: { threadId: string }) {
58 const { messages, isHydrating, sendMessage } = useChat({
59 threadId,
60 connection: fetchServerSentEvents('/api/chat'),
61 persistence: true,
62 })
63 if (isHydrating) return <p>Loading conversation...</p>
64 return (
65 <div>
66 {messages.map((message) => (
67 <div key={message.id}>{message.role}</div>
68 ))}
69 <button type="button" onClick={() => void sendMessage('hi')}>
70 Send
71 </button>
72 </div>
73 )
74 }
75 ```
76​
772. Add a `GET` next to your chat `POST`:
78​
79 ```ts
80 import { memoryStream, resumeServerSentEventsResponse } from '@tanstack/ai'
81 import { reconstructChat } from '@tanstack/ai-persistence'
82 import { persistence } from './persistence'
83​
84 export function GET(request: Request): Response | Promise<Response> {
85 const durability = memoryStream(request)
86 // A reconnecting client sends a resume cursor. Replay the log.
87 if (durability.resumeFrom() !== null) {
88 return resumeServerSentEventsResponse({ adapter: durability })
89 }
90 // Otherwise return the stored thread, plus any run that still streams.
91 return reconstructChat(persistence, request, {
92 // Without this, anyone who guesses a thread id gets the transcript.
93 authorize: async (threadId, req) => ownsThread(req, threadId),
94 })
95 }
96​
97 async function ownsThread(request: Request, threadId: string): Promise<boolean> {
98 void request
99 void threadId
100 return true // Replace with your session and ownership check.
101 }
102 ```
103​
104The replay branch works only when your `POST` records the stream. To record it, pass `{ durability: { adapter: memoryStream(request) } }` to `toServerSentEventsResponse` in the `POST`. The [overview quick setup](./overview#quick-setup) shows the full route.
105​
106Reload the page. `useChat` loads the thread from the server. Open the same `threadId` on another device, and you get the same chat.
107​
108You do not fetch or seed the transcript yourself. You need no loader and no `initialMessages`. The `threadId` is the stable key, and the server finds everything from it.
109​
110## Pick a stable thread id
111​
112The `threadId` is the key that the record is saved under. A new id on each mount restores nothing. Take it from your own data, for example a conversation id or a route param. [Id map](./id-map) explains how to choose one, and how it differs from the `runId` that the hook reports.
113​
114## What a reload restores
115​
116- **The transcript.** It shows again from storage or from the server.
117- **A pending interrupt.** An approval prompt comes back as it was.
118- **A reply that was still streaming.** It finishes in place. This needs a durability-backed connection: a route that records the stream and has a replay handler. See [Resumable streams](../resumable-streams/overview).
119​
120Replay rebuilds reasoning, tool activity, and text from the durable log. This includes runs that emit reasoning before their first tool or text event. The completed activity stays in the transcript that the next message sends.
121​
122## Choose a mode
123​
124`persistence` takes a storage adapter or a boolean:
125​
126| Value | Who owns the history | What the client caches | Use it for |
127| --- | --- | --- | --- |
128| A storage adapter | The client | The transcript and a resume pointer | Single-page and offline apps, one device, small to medium history |
129| `true` | The server | Nothing | Large histories, many devices, no transcripts in the browser |
130| `false` or omitted | Nobody | Nothing | A chat that can start empty after a reload |
131​
132The generation hooks take the same option, but as a boolean only. See [Generation persistence](./generation-persistence).
133​
134Client and server persistence are independent:
135​
136- Client persistence restores what one browser showed.
137- Server persistence ([Chat persistence](./chat-persistence)) keeps the true copy for every user, and survives a server restart.
138​
139For the setup that most apps use, see [Which setup do I want?](./overview#which-setup-do-i-want).
140​
141## Choose a storage backend
142​
143Three adapters ship in `@tanstack/ai-client`. Every framework package exports them again. They all have the same shape:
144​
145| Adapter | How long it keeps data | Notes | Use it for |
146| --- | --- | --- | --- |
147| `localStoragePersistence` | Across reloads and browser restarts | Synchronous, about 5MB quota, JSON codec | The default: keep a conversation for next time |
148| `sessionStoragePersistence` | One tab, until the tab closes | Same shape as localStorage | A chat that must not outlive the tab |
149| `indexedDBPersistence` | Across reloads and restarts | Async, structured clone (a `Date` comes back exactly), room for large data | Big transcripts, or values that a JSON codec changes |
150​
151```tsx
152import { indexedDBPersistence } from '@tanstack/ai-react'
153​
154const persistence = indexedDBPersistence()
155```
156​
157Each adapter throws only when you use it and its browser store is missing, for example during server-side rendering. So you can create one on the server safely.
158​
159## Advanced
160​
161### Page a long thread
162​
163With `persistence: true`, `history: { pageSize }` loads only the newest messages on hydrate. Call `loadOlderMessages()` for more:
164​
165```tsx
166import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
167​
168const connection = fetchServerSentEvents('/api/chat')
169​
170function Chat({ threadId }: { threadId: string }) {
171 const {
172 messages,
173 isHydrating,
174 hasOlderMessages,
175 loadOlderMessages,
176 sendMessage,
177 } = useChat({
178 threadId,
179 connection,
180 persistence: true,
181 history: { pageSize: 50 },
182 })
183 if (isHydrating) return <p>Loading conversation...</p>
184 return (
185 <div>
186 {hasOlderMessages ? (
187 <button
188 type="button"
189 onClick={() => {
190 void loadOlderMessages().catch(() => {
191 // Show a retry. The messages on screen stay.
192 })
193 }}
194 >
195 Load older
196 </button>
197 ) : null}
198 {messages.map((m) => (
199 <div key={m.id}>{m.role}</div>
200 ))}
201 <button type="button" onClick={() => void sendMessage('hi')}>
202 Send
203 </button>
204 </div>
205 )
207```
208​
209The library does not watch the scrollbar. Call `loadOlderMessages()` from your own scroll handler.
210​
211- `history` is valid only with `persistence: true`. Without `history`, hydrate loads the full thread.
212- `hasOlderMessages` follows `page.truncated` from the last hydrate or older-page response.
213- With `history.pageSize`, a send posts only the new turn. A reload posts the last user message, because the old assistant message is already gone in the client. A resume posts from that user message through the assistant message on screen, so the stored tool call stays.
214- If `loadOlderMessages()` fails, the promise rejects, the messages on screen stay, and `hasOlderMessages` stays `true`. Catch the rejection in your UI.
215​
216### Loading state
217​
218`isHydrating` is `true` from the first render until the transcript is in place.
219​
220- If a run still generates, `isLoading` is already `true` when `isHydrating` turns `false`.
221- If the load fails, `isHydrating` turns `false` and `error` is set.
222​
223When the transcript appears depends on the adapter and the framework:
224​
225- A direct `ChatClient` and most framework wrappers load sync adapters (`localStorage`, `sessionStorage`) during construction.
226- React is different. The first committed render uses `initialMessages` and `initialResumeSnapshot`, and browser persistence applies after the hook attaches. This keeps the server snapshot stable during SSR hydration.
227- IndexedDB always loads asynchronously, after the database opens.
228​
229### What `reconstructChat` returns
230​
231`reconstructChat` returns a JSON body with these fields:
232​
233- `messages`: the transcript as UI messages.
234- `activeRun`: `{ runId }` when a run still generates for the thread, else `null`. The client follows it through the replay branch of the `GET`.
235- `interrupts`: the pending interrupts and the run they paused, else `null`. Needs an `interrupts` store.
236- `page`: `{ truncated, cursor }`, only when the request has a valid `limit` query param. `reconstructChat` reads `limit` and `before` from the query.
237​
238You never handle a run id. A second device resumes the live run the same way the first tab does.
239​
240### Show how long each turn took
241​
242A live turn can time itself on the client. After a reload, that time is gone. Pass `includeRuns: true` to get it back from the server:
243​
244```ts
245import { reconstructChat } from '@tanstack/ai-persistence'
246import { persistence } from './persistence'
247​
248export function GET(request: Request): Promise<Response> {
249 return reconstructChat(persistence, request, { includeRuns: true })
251```
252​
253Each assistant message of a finished run then has the run timings, in epoch ms, on `metadata.tanstack.run`:
254​
255```tsx
256import type { UIMessage } from '@tanstack/ai'
257​
258function TurnDuration({ message }: { message: UIMessage }) {
259 const run = message.metadata?.tanstack?.run
260 if (!run?.finishedAt) return null
261 const seconds = Math.round((run.finishedAt - run.startedAt) / 1000)
262 return <span>Worked for {seconds}s</span>
264```
265​
266The response also has a top-level `runs` list with `runId`, `status`, `startedAt`, and `finishedAt` for each finished run. The timings need:
267​
268- A `runs` store that implements `listByThread`.
269- Messages that `withPersistence` saved with this version or later.
270​
271### AG-UI activity rows
272​
273AG-UI activity events show as `role: 'activity'` rows in `messages`.
274​
275- A client storage adapter keeps each row with the same `id` and content.
276- `persistence: true` restores the rows from the server only when the server has an `activities` store. See [AG-UI activity rows on reload](./chat-persistence-advanced#ag-ui-activity-rows-on-reload).
277​
278The next `sendMessage` does not send activity rows as model input.
279​
280### Handle restored client tools
281​
282A live client tool runs when its call arrives from the stream. Hydration restores its pending execution, but it does not run the browser code again, because that work is not always safe to repeat. The execution stays an internal interrupt, and it is not in `interrupts`.
283​
284Use `onInterruptStateChange` to tell restored interrupt state from live updates. By default, a restored batch stays pending. This example cancels every restored batch:
285​
286```tsx
287import { useEffect, useState } from 'react'
288import {
289 fetchServerSentEvents,
290 localStoragePersistence,
291 useChat,
292} from '@tanstack/ai-react'
293​
294function Chat() {
295 const [restoredBatch, setRestoredBatch] = useState(false)
296 const { cancelInterrupts } = useChat({
297 threadId: 'support-chat',
298 connection: fetchServerSentEvents('/api/chat'),
299 persistence: localStoragePersistence(),
300 onInterruptStateChange(_state, { source }) {
301 setRestoredBatch(source === 'hydrate')
302 },
303 })
304​
305 useEffect(() => {
306 if (restoredBatch) cancelInterrupts()
307 }, [cancelInterrupts, restoredBatch])
308​
309 return null
311```
312​
313- `source` is `hydrate` for state from an initial resume snapshot, a client storage adapter, or server hydration.
314- `source` is `live` for streamed changes and changes that the client starts.
315​
316`cancelInterrupts()` cancels the full internal batch. That includes visible approvals and hidden client-tool executions. It cannot cancel only one kind of interrupt.
317​
318### Write your own storage adapter
319​
320Any object with `getItem`, `setItem`, and `removeItem` works. The record is one `{ messages, resume? }` object per chat id: the transcript, plus the pointer that lets a reload rejoin a running reply. So `setItem` gets that full record, not a bare message array:
321​
322```ts
323import type {
324 ChatClientPersistence,
325 ChatPersistedState,
326} from '@tanstack/ai-client'
327​
328function isPersistedState(value: unknown): value is ChatPersistedState {
329 return (
330 typeof value === 'object' &&
331 value !== null &&
332 'messages' in value &&
333 Array.isArray(value.messages)
334 )
336​
337const persistence: ChatClientPersistence = {
338 getItem(id) {
339 const raw = localStorage.getItem(id)
340 if (raw === null) return null
341 const parsed: unknown = JSON.parse(raw)
342 // Wrap a bare message array saved by a 0.x app.
343 if (Array.isArray(parsed)) return { messages: parsed }
344 return isPersistedState(parsed) ? parsed : null
345 },
346 setItem(id, state) {
347 localStorage.setItem(id, JSON.stringify(state))
348 },
349 removeItem(id) {
350 localStorage.removeItem(id)
351 },
353```
354​
355> [!WARNING]
356> Reads are best effort. If `getItem` throws or returns `null`, the client treats it as "nothing stored". So an adapter that parses the wrong shape fails **silently**, and the conversation does not come back. Do one real reload with your adapter before you ship it.