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

overview.md

194 lines7.4 KB

1---
2title: Persistence Overview
3id: overview
4description: "Set up persistence for chat, generation and sandboxes: one server route, one client option. Copy the snippets, then read the details only if you need them."
5keywords:
6 - persistence
7 - durability
8 - rehydrate conversation
9 - page reload
10 - server authoritative
11 - client authoritative
12---
13​
14Your user reloads the page and the conversation is gone, because it only ever lived
15in memory. Or they open the app on their phone and none of it is there. Persistence
16fixes both, and it is two snippets: one middleware on the server, one option on the
17client.
18​
19There is a second, separate problem: the socket drops while a reply is still
20streaming. That is [Resumable Streams](../resumable-streams/overview), a different
21layer you can add on its own. Step 3 below combines them, which is what most apps
22end up wanting.
23​
24When the provider sandbox is gone, the workspace files can also disappear. Use
25the same persistence object with
26[Keep Files After Reload](../sandbox/portable-snapshots-configure).
27​
28## Install
29​
30<!-- ::start:tabs variant="package-manager" mode="install" -->
31​
32react: @tanstack/ai-persistence
33vue: @tanstack/ai-persistence
34solid: @tanstack/ai-persistence
35svelte: @tanstack/ai-persistence
36preact: @tanstack/ai-persistence
37angular: @tanstack/ai-persistence
38vanilla: @tanstack/ai-persistence
39octane: @tanstack/ai-persistence
40​
41<!-- ::end:tabs -->
42​
43The client half needs no install. It ships in the framework package you already use
44(`@tanstack/ai-react`, `-vue`, `-solid`, `-svelte`, `-angular`, or
45`@tanstack/ai-client`).
46​
47Wire this package's [Agent Skills](../getting-started/agent-skills) into your coding
48assistant before you write any of it, then ask it for "add chat persistence to this
49app":
50​
51```bash
52npx @tanstack/intent@latest install
53```
54​
55Run that after the package is installed. Intent scans `node_modules`, so anything
56added later needs another run.
57​
58## 1. Server: store the conversation
59​
60`withPersistence` writes the transcript, run status and any pending approvals into
61your own store. `persistence` here is your adapter;
62[build one](./build-your-own-adapter) in about 40 lines, use a
63[third-party adapter](./build-your-own-adapter#third-party-adapters), or start with
64`memoryPersistence()` for local dev.
65​
66```ts
67import {
68 chat,
69 chatParamsFromRequest,
70 toServerSentEventsResponse,
71} from '@tanstack/ai'
72import { openaiText } from '@tanstack/ai-openai'
73import { withPersistence } from '@tanstack/ai-persistence'
74import { persistence } from './persistence'
75​
76export async function POST(request: Request) {
77 const params = await chatParamsFromRequest(request)
78 const stream = chat({
79 adapter: openaiText('gpt-5.5'),
80 messages: params.messages,
81 threadId: params.threadId,
82 runId: params.runId,
83 ...(params.resume ? { resume: params.resume } : {}),
84 middleware: [withPersistence(persistence)],
85 })
86 return toServerSentEventsResponse(stream)
88```
89​
90## 2. Client: bring it back
91​
92Two forms, and the choice is only about who owns the history:
93​
94- **`persistence: true`** puts the server in charge. The browser caches nothing and
95 asks the server for the thread on mount. Best for multi-user and multi-device apps.
96- **`persistence: <adapter>`** puts the browser in charge, with
97 `localStoragePersistence()`, `sessionStoragePersistence()` or
98 `indexedDBPersistence()`. No server store needed.
99​
100```tsx
101import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
102​
103function Chat() {
104 const { messages, sendMessage } = useChat({
105 threadId: 'support-chat',
106 connection: fetchServerSentEvents('/api/chat'),
107 persistence: true,
108 // Or keep the transcript in the browser instead:
109 // persistence: localStoragePersistence(),
110 })
111 return <button onClick={() => sendMessage('hi')}>{messages.length}</button>
113```
114​
115With `persistence: true` the client needs one `GET` to read from, which is step 3.
116With a storage adapter you are done: reload and the conversation is there.
117​
118A long thread can page on hydrate. See [Client persistence](./client-persistence)
119for `history: { pageSize }`.
120​
121## 3. Survive a reload mid-answer
122​
123Add a `GET` to the same route. It does two jobs, and the `if` picks one per request:
124replay a run that is still streaming, or hand back the stored transcript.
125​
126```ts
127import {
128 chatParamsFromRequest,
129 memoryStream,
130 resumeServerSentEventsResponse,
131} from '@tanstack/ai'
132import { reconstructChat } from '@tanstack/ai-persistence'
133import { persistence } from './persistence'
134​
135export function GET(request: Request): Response | Promise<Response> {
136 const durability = memoryStream(request)
137 // A run still in flight: the client sent a resume offset, so replay its log.
138 if (durability.resumeFrom() !== null) {
139 return resumeServerSentEventsResponse({ adapter: durability })
140 }
141 // Otherwise return the stored thread, plus a cursor to any run still generating.
142 return reconstructChat(persistence, request, {
143 // WITHOUT this, anyone who guesses a thread id gets the whole transcript.
144 authorize: async (threadId, req) => ownsThread(req, threadId),
145 })
147​
148async function ownsThread(request: Request, threadId: string): Promise<boolean> {
149 void request
150 void threadId
151 return true // replace with your session and ownership check
153```
154​
155`useChat` drives both halves for you. On mount it fetches the transcript, and if the
156server reports a run still generating, it tails that run and the reply finishes in
157place. Nothing else to wire, and a second device follows the identical path.
158​
159To make the `POST` resumable too, hand the same adapter to the response:
160`toServerSentEventsResponse(stream, { durability: { adapter: memoryStream(request) } })`.
161​
162## Generation and sandboxes use the same idea
163​
164- **Generation** (image, video, speech, transcription): the hooks take a
165 `persistence` option too, boolean only, backed by a `generationRuns` store. See
166 [Generation persistence](./generation-persistence), and
167 [Keep generated files](./keep-generated-files) to hold the bytes after the
168 provider's URLs expire.
169- **Sandboxed agents**: a run can outlive the tab and be adopted by another host.
170 See [Build a Sandbox Adapter](./build-a-sandbox-adapter) for what to
171 store, and [Durable Runs](../sandbox/durable-runs) for why.
172​
173## Which setup do I want?
174​
175| You want | Turn on |
176| --- | --- |
177| The conversation to survive a reload, nothing more | Step 2 with a storage adapter |
178| The same conversation on another device, or after a server restart | Steps 1 and 2 with `persistence: true` |
179| A reload mid-answer to pick the answer back up | Steps 1, 2 and 3 |
180| A dropped socket to resume with the page still open | [Resumable Streams](../resumable-streams/overview) alone |
181| To pause for a human approval and resume it days later | Step 1 with an `interrupts` store |
182| Sandbox files to come back after the provider sandbox is gone | [Keep Files After Reload](../sandbox/portable-snapshots-configure) |
183​
184## Where to go next
185​
186- [Chat persistence](./chat-persistence): the server middleware in full, including
187 durable interrupts.
188- [Client persistence](./client-persistence): the modes, storage backends, and what a
189 reload restores in each case.
190- [Build your own adapter](./build-your-own-adapter): implement the stores against
191 your database and prove them with the conformance suite.
192- [Controls](./controls): compose backends per store.
193- [How persistence works](./internals): the two layers, thread and run identity, who
194 owns history, and the middleware lifecycle. Read it when something surprises you.