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