Open History to see the last commit
1---
2title: Client Persistence
3id: client-persistence
4---
5
6A `ChatClient` (and every framework `useChat` / `createChat`) keeps messages in
7memory, so a reload or a crashed tab loses the whole conversation and any reply
8that was still streaming. The `persistence` option fixes that from the browser
9side: on reload it repaints the transcript, brings back a pending interrupt, and
10rejoins a run that was mid-stream.
11
12You need this whether or not you have a server:
13
14- **The browser owns the chat** (SPA, offline-first, no server store). Pass a
15 storage adapter and it holds the full transcript, restored on reload with no
16 network.
17- **The server owns the chat** (you use [Chat persistence](./chat-persistence)).
18 Set `persistence: true` and the client caches nothing: on reload it hydrates
19 the thread from the server by its `threadId`, painting the conversation and
20 rejoining any run still streaming. That is the server-authoritative mode below.
21
22## Turn it on
23
24Pass a storage adapter as `persistence` and give the chat a stable `threadId` so
25a reload finds the same record:
26
27```tsx
28import {
29 fetchServerSentEvents,
30 localStoragePersistence,
31 useChat,
32} from '@tanstack/ai-react'
33
34function Chat() {
35 const { messages, sendMessage } = useChat({
36 threadId: 'support-chat',
37 connection: fetchServerSentEvents('/api/chat'),
38 persistence: localStoragePersistence(),
39 })
40 // ...render messages, call sendMessage(text)
41}
42```
43
44`localStoragePersistence()` needs no type argument and no codec: it defaults to
45the chat record shape and a JSON codec. That is the whole opt-in.
46
47The `threadId` is doing the real work here: it is the key the record is written
48under and looked up by, so a fresh id per mount restores nothing. Derive it from
49your own domain (a conversation id, a route param). [Id map](./id-map) covers how
50to pick one and how it differs from the `runId` the hook reports.
51
52## What a reload restores
53
54The client stores one record per `threadId`, the transcript plus a small resume
55pointer. On the next load `useChat` reads it and:
56
57- **Repaints the transcript** from storage with no network. A direct
58 `ChatClient` and most framework wrappers hydrate sync adapters
59 (`localStorage` / `sessionStorage`) during construction. React is
60 different: the first committed render uses `initialMessages` and
61 `initialResumeSnapshot`, and browser persistence is applied after the hook
62 attaches. This keeps the server snapshot stable during SSR hydration.
63 IndexedDB always hydrates asynchronously after the database opens. Until the
64 stored transcript is applied, `isHydrating` is `true`, so you can show a
65 loading state instead of an empty chat.
66- **Rehydrates a pending interrupt**, so an approval prompt comes back exactly as
67 it was.
68- **Rejoins an in-flight run**, if a reply was still streaming when the page
69 reloaded, so it finishes in place instead of freezing half-done. This one needs
70 a durability-backed connection (a route that records the stream and exposes a
71 replay handler); see [Resumable streams](../resumable-streams/overview).
72
73Replay rebuilds reasoning, tool activity, and text from the durable log, including runs that emit reasoning before their first tool or text event. The completed activity remains in the transcript sent with the next message.
74
75### AG-UI activity rows
76
77AG-UI activity events show as `role: 'activity'` rows in `messages`.
78
79- A client storage adapter keeps each row with the same `id` and content.
80- `persistence: true` restores the rows from the server only when the server
81 has an `activities` store. See
82 [AG-UI activity rows on reload](./chat-persistence#ag-ui-activity-rows-on-reload).
83
84The next `sendMessage` does not send activity rows as model input.
85
86### Handle restored client tools
87
88A live client tool runs automatically when its call arrives from the stream.
89Hydration restores its pending execution but does not run the browser code
90again, because that work may not be safe to repeat. The execution remains an
91internal interrupt and does not appear in `interrupts`.
92
93Use `onInterruptStateChange` to distinguish restored interrupt state from live
94updates. Leaving a restored batch pending is the default. This example cancels
95every restored batch instead:
96
97```tsx
98import { useEffect, useState } from 'react'
99import {
100 fetchServerSentEvents,
101 localStoragePersistence,
102 useChat,
103} from '@tanstack/ai-react'
104
105function Chat() {
106 const [restoredBatch, setRestoredBatch] = useState(false)
107 const { cancelInterrupts } = useChat({
108 threadId: 'support-chat',
109 connection: fetchServerSentEvents('/api/chat'),
110 persistence: localStoragePersistence(),
111 onInterruptStateChange(_state, { source }) {
112 setRestoredBatch(source === 'hydrate')
113 },
114 })
115
116 useEffect(() => {
117 if (restoredBatch) cancelInterrupts()
118 }, [cancelInterrupts, restoredBatch])
119
120 return null
121}
122```
123
124`source` is `hydrate` for state restored from an initial resume snapshot, a
125client storage adapter, or server hydration. It is `live` for streamed and
126client-initiated changes. `cancelInterrupts()` cancels the complete internal
127batch, including visible approvals and hidden client-tool executions; it does
128not selectively cancel one kind of interrupt.
129
130## Choose a mode
131
132`persistence` takes a storage adapter or a boolean:
133
134- an **adapter** (`persistence: localStoragePersistence()`) is client-authoritative.
135- **`true`** is server-authoritative.
136- **`false`** (or omitted) is off: messages live in memory only and a reload starts empty.
137
138The generation hooks take the same option, boolean only. See
139[Generation persistence](./generation-persistence).
140
141### An adapter: client-authoritative
142
143Pass the adapter directly, `persistence: localStoragePersistence()`. The
144transcript and the resume pointer both live in the browser. The client owns the
145history; the server, if any, mirrors it. Best when the browser is the source of
146truth: single-page apps, offline-first, one device, small to moderate
147conversations.
148
149### `true`: server-authoritative
150
151Pass `persistence: true`. The client stores nothing, no transcript and no resume
152pointer. On mount `useChat` hydrates the thread from the server by its
153`threadId`: it paints the stored transcript and, if a run is still generating,
154tails it to completion. `history: { pageSize }` paints the newest window on
155hydrate. Best when transcripts are large (localStorage is
156synchronous and quota-bound), when the same conversation must open on another
157device, or when you simply do not want message content in the browser.
158
159You do not fetch or seed the transcript yourself. A reload and the same thread
160opened on another device follow the identical path, because the thread id is the
161stable key and the server resolves everything from it. No loader, no
162`initialMessages`, no extra props. It needs a connection with a `hydrate` handler
163(every built-in connection has one) and the server `GET` endpoint below.
164
165**Client**: a connection, a stable `threadId`, and `persistence: true`:
166
167```tsx
168import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
169
170const connection = fetchServerSentEvents('/api/chat')
171
172function Chat({ threadId }: { threadId: string }) {
173 const {
174 messages,
175 isHydrating,
176 hasOlderMessages,
177 loadOlderMessages,
178 sendMessage,
179 } = useChat({
180 threadId,
181 connection,
182 persistence: true,
183 history: { pageSize: 50 },
184 })
185 if (isHydrating) return <p>Loading conversation...</p>
186 return (
187 <div>
188 {hasOlderMessages ? (
189 <button
190 type="button"
191 onClick={() => {
192 void loadOlderMessages().catch(() => {
193 // Show a retry. Painted messages stay.
194 })
195 }}
196 >
197 Load older
198 </button>
199 ) : null}
200 {messages.map((m) => (
201 <div key={m.id}>{m.role}</div>
202 ))}
203 <button type="button" onClick={() => void sendMessage('hi')}>
204 Send
205 </button>
206 </div>
207 )
208}
209```
210
211Call `loadOlderMessages()` from your scroll handler. The library does not watch
212the scrollbar.
213
214- `isHydrating` is `true` from the first render until the transcript is in
215 place. If a run is still generating, `isLoading` is already `true` when
216 `isHydrating` turns `false`. If the load fails, `isHydrating` turns `false`
217 and `error` is set.
218- `hasOlderMessages` follows `page.truncated` on the last hydrate or older-page
219 response.
220- Without `history`, hydrate loads the full thread.
221- `history` is only valid with `persistence: true`.
222- With `history.pageSize`, send posts only the new turn. Reload posts the last
223 user (the old assistant is already gone locally). Resume posts from that
224 user through the painted assistant so the stored tool-call is not dropped.
225- If `loadOlderMessages()` fails, the promise rejects and painted messages
226 stay. `hasOlderMessages` stays true. Catch the rejection in your UI.
227
228**Server**: one `GET` endpoint next to your chat `POST`. Replay the durability
229log when the request carries a resume cursor, otherwise return the stored
230conversation with `reconstructChat`:
231
232```ts
233import { memoryStream, resumeServerSentEventsResponse } from '@tanstack/ai'
234import { reconstructChat } from '@tanstack/ai-persistence'
235import { persistence } from './persistence'
236
237export function GET(request: Request): Response | Promise<Response> {
238 const durability = memoryStream(request)
239 // A reconnecting client carries a resume cursor (Last-Event-ID / ?offset and
240 // X-Run-Id / ?runId). Replay the log so the run finishes in place.
241 if (durability.resumeFrom() !== null) {
242 return resumeServerSentEventsResponse({ adapter: durability })
243 }
244 // Otherwise return the stored transcript plus a cursor to any in-flight run.
245 // Guard access in multi-user apps (see authorize in Chat persistence).
246 return reconstructChat(persistence, request)
247}
248```
249
250`reconstructChat` returns `{ messages, activeRun }`: the transcript as UI
251messages, and `activeRun` when a run is still generating for the thread. With a
252valid `limit` query param, the body also has `page: { truncated, cursor }`.
253`reconstructChat` reads `limit` and `before` from the query.
254
255The client calls this endpoint on mount and, when `activeRun` is set, tails the
256run through the replay branch above. You never handle a run id, and a second
257device resumes the live run the same way the original tab does. See
258[Chat persistence](./chat-persistence).
259
260### Show how long each turn took
261
262A 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:
263
264```ts
265import { reconstructChat } from '@tanstack/ai-persistence'
266import { persistence } from './persistence'
267
268export function GET(request: Request): Promise<Response> {
269 return reconstructChat(persistence, request, { includeRuns: true })
270}
271```
272
273Each assistant message of a finished run then has the run's timings, in epoch ms, on `metadata.tanstack.run`:
274
275```tsx
276import type { UIMessage } from '@tanstack/ai'
277
278function TurnDuration({ message }: { message: UIMessage }) {
279 const run = message.metadata?.tanstack?.run
280 if (!run?.finishedAt) return null
281 const seconds = Math.round((run.finishedAt - run.startedAt) / 1000)
282 return <span>Worked for {seconds}s</span>
283}
284```
285
286The response also has a top-level `runs` list with `runId`, `status`, `startedAt`, and `finishedAt` for each finished run. The timings need a `runs` store that implements `listByThread`, and messages that were saved by `withPersistence` with this version or later.
287
288| Mode | Caches on client | Authoritative history | Reach for it when |
289| --- | --- | --- | --- |
290| `persistence: store` | transcript + resume pointer | client | SPA / offline, one device, small to moderate history |
291| `persistence: true` | nothing | server | large histories, multi-device, no transcripts in the browser |
292
293## Choose a storage backend
294
295Three adapters ship from `@tanstack/ai-client`, re-exported from every framework
296package. All share the same shape; they differ in lifetime and encoding.
297
298| Adapter | Lifetime | Notes | Reach for it when |
299| --- | --- | --- | --- |
300| `localStoragePersistence` | across reloads and browser restarts | synchronous, ~5MB quota, JSON codec | the default: persist a conversation for next time |
301| `sessionStoragePersistence` | one tab, cleared when it closes | same shape as localStorage | a conversation that should not outlive the tab |
302| `indexedDBPersistence` | across reloads and restarts | async, structured clone (a `Date` round-trips exactly), room for large data | big transcripts, or values a JSON codec would mangle |
303
304```tsx
305import { indexedDBPersistence } from '@tanstack/ai-react'
306
307const persistence = indexedDBPersistence()
308```
309
310Each throws only lazily, per operation, when its backing store is missing (for
311example during server-side rendering), so constructing one on the server is safe.
312
313### Writing your own
314
315Any object with `getItem` / `setItem` / `removeItem` works. The record is one
316`{ messages, resume? }` blob per chat id (the transcript plus the pointer that
317lets a reload rejoin an in-flight run), so `setItem` receives that whole record,
318not a bare message array:
319
320```ts
321import type {
322 ChatClientPersistence,
323 ChatPersistedState,
324} from '@tanstack/ai-client'
325
326function isPersistedState(value: unknown): value is ChatPersistedState {
327 return (
328 typeof value === 'object' &&
329 value !== null &&
330 'messages' in value &&
331 Array.isArray(value.messages)
332 )
333}
334
335const persistence: ChatClientPersistence = {
336 getItem(id) {
337 const raw = localStorage.getItem(id)
338 if (raw === null) return null
339 const parsed: unknown = JSON.parse(raw)
340 // A bare array is the legacy messages-only format, still accepted.
341 if (Array.isArray(parsed)) return { messages: parsed }
342 return isPersistedState(parsed) ? parsed : null
343 },
344 setItem(id, state) {
345 localStorage.setItem(id, JSON.stringify(state))
346 },
347 removeItem(id) {
348 localStorage.removeItem(id)
349 },
350}
351```
352
353Reads are best-effort: a `getItem` that throws or returns `null` is treated as
354"nothing stored", so an adapter that parses the wrong shape fails **silently**:
355the conversation just does not come back. Round-trip your adapter once against a
356real reload before shipping it.
357
358## Client and server are independent
359
360Client persistence restores what one browser rendered. Server persistence
361([Chat persistence](./chat-persistence)) keeps the authoritative copy for every
362user and survives a server restart. They compose: for the combination we
363recommend for most apps, and why, see the
364[Persistence overview](./overview#what-we-recommend).