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

overview.md

193 lines7.3 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, or start with
63`memoryPersistence()` for local dev.
64​
65```ts
66import {
67 chat,
68 chatParamsFromRequest,
69 toServerSentEventsResponse,
70} from '@tanstack/ai'
71import { openaiText } from '@tanstack/ai-openai'
72import { withPersistence } from '@tanstack/ai-persistence'
73import { persistence } from './persistence'
74​
75export async function POST(request: Request) {
76 const params = await chatParamsFromRequest(request)
77 const stream = chat({
78 adapter: openaiText('gpt-5.5'),
79 messages: params.messages,
80 threadId: params.threadId,
81 runId: params.runId,
82 ...(params.resume ? { resume: params.resume } : {}),
83 middleware: [withPersistence(persistence)],
84 })
85 return toServerSentEventsResponse(stream)
87```
88​
89## 2. Client: bring it back
90​
91Two forms, and the choice is only about who owns the history:
92​
93- **`persistence: true`** puts the server in charge. The browser caches nothing and
94 asks the server for the thread on mount. Best for multi-user and multi-device apps.
95- **`persistence: <adapter>`** puts the browser in charge, with
96 `localStoragePersistence()`, `sessionStoragePersistence()` or
97 `indexedDBPersistence()`. No server store needed.
98​
99```tsx
100import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
101​
102function Chat() {
103 const { messages, sendMessage } = useChat({
104 threadId: 'support-chat',
105 connection: fetchServerSentEvents('/api/chat'),
106 persistence: true,
107 // Or keep the transcript in the browser instead:
108 // persistence: localStoragePersistence(),
109 })
110 return <button onClick={() => sendMessage('hi')}>{messages.length}</button>
112```
113​
114With `persistence: true` the client needs one `GET` to read from, which is step 3.
115With a storage adapter you are done: reload and the conversation is there.
116​
117A long thread can page on hydrate. See [Client persistence](./client-persistence)
118for `history: { pageSize }`.
119​
120## 3. Survive a reload mid-answer
121​
122Add a `GET` to the same route. It does two jobs, and the `if` picks one per request:
123replay a run that is still streaming, or hand back the stored transcript.
124​
125```ts
126import {
127 chatParamsFromRequest,
128 memoryStream,
129 resumeServerSentEventsResponse,
130} from '@tanstack/ai'
131import { reconstructChat } from '@tanstack/ai-persistence'
132import { persistence } from './persistence'
133​
134export function GET(request: Request): Response | Promise<Response> {
135 const durability = memoryStream(request)
136 // A run still in flight: the client sent a resume offset, so replay its log.
137 if (durability.resumeFrom() !== null) {
138 return resumeServerSentEventsResponse({ adapter: durability })
139 }
140 // Otherwise return the stored thread, plus a cursor to any run still generating.
141 return reconstructChat(persistence, request, {
142 // WITHOUT this, anyone who guesses a thread id gets the whole transcript.
143 authorize: async (threadId, req) => ownsThread(req, threadId),
144 })
146​
147async function ownsThread(request: Request, threadId: string): Promise<boolean> {
148 void request
149 void threadId
150 return true // replace with your session and ownership check
152```
153​
154`useChat` drives both halves for you. On mount it fetches the transcript, and if the
155server reports a run still generating, it tails that run and the reply finishes in
156place. Nothing else to wire, and a second device follows the identical path.
157​
158To make the `POST` resumable too, hand the same adapter to the response:
159`toServerSentEventsResponse(stream, { durability: { adapter: memoryStream(request) } })`.
160​
161## Generation and sandboxes use the same idea
162​
163- **Generation** (image, video, speech, transcription): the hooks take a
164 `persistence` option too, boolean only, backed by a `generationRuns` store. See
165 [Generation persistence](./generation-persistence), and
166 [Keep generated files](./keep-generated-files) to hold the bytes after the
167 provider's URLs expire.
168- **Sandboxed agents**: a run can outlive the tab and be adopted by another host.
169 See [Build a Sandbox Adapter](./build-a-sandbox-adapter) for what to
170 store, and [Durable Runs](../sandbox/durable-runs) for why.
171​
172## Which setup do I want?
173​
174| You want | Turn on |
175| --- | --- |
176| The conversation to survive a reload, nothing more | Step 2 with a storage adapter |
177| The same conversation on another device, or after a server restart | Steps 1 and 2 with `persistence: true` |
178| A reload mid-answer to pick the answer back up | Steps 1, 2 and 3 |
179| A dropped socket to resume with the page still open | [Resumable Streams](../resumable-streams/overview) alone |
180| To pause for a human approval and resume it days later | Step 1 with an `interrupts` store |
181| Sandbox files to come back after the provider sandbox is gone | [Keep Files After Reload](../sandbox/portable-snapshots-configure) |
182​
183## Where to go next
184​
185- [Chat persistence](./chat-persistence): the server middleware in full, including
186 durable interrupts.
187- [Client persistence](./client-persistence): the modes, storage backends, and what a
188 reload restores in each case.
189- [Build your own adapter](./build-your-own-adapter): implement the stores against
190 your database and prove them with the conformance suite.
191- [Controls](./controls): compose backends per store.
192- [How persistence works](./internals): the two layers, thread and run identity, who
193 owns history, and the middleware lifecycle. Read it when something surprises you.