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

overview.md

186 lines6.7 KB

1---
2title: Persistence Overview
3id: overview
4description: "Keep a chat after a page reload or on another device. Add one middleware on the server and one option on the client."
5keywords:
6 - persistence
7 - durability
8 - rehydrate conversation
9 - page reload
10 - server authoritative
11 - client authoritative
12---
13​
14Persistence stores the conversation outside process memory. A reload, or the same user on another device, then loads that conversation.
15​
16The server saves each thread, and `useChat` loads it back when the page opens.
17​
18## Quick setup
19​
20This setup keeps the chat on the server. It also lets a reply that was still streaming finish after a reload. It takes about five minutes.
21​
22### 1. Install the package
23​
24<!-- ::start:tabs variant="package-manager" mode="install" -->
25​
26react: @tanstack/ai-persistence
27vue: @tanstack/ai-persistence
28solid: @tanstack/ai-persistence
29svelte: @tanstack/ai-persistence
30preact: @tanstack/ai-persistence
31angular: @tanstack/ai-persistence
32vanilla: @tanstack/ai-persistence
33octane: @tanstack/ai-persistence
34​
35<!-- ::end:tabs -->
36​
37The client half ships in the framework package you already use.
38​
39### 2. Create the persistence object
40​
41Make one object for the whole app. `memoryPersistence()` keeps everything in process memory, which is good for local development:
42​
43```ts
44// persistence.ts
45import { memoryPersistence } from '@tanstack/ai-persistence'
46​
47export const persistence = memoryPersistence()
48```
49​
50### 3. Save and load on the server
51​
52Add `withPersistence` to your chat `POST`. Then add a `GET` on the same route:
53​
54```ts
55// api/chat.ts
56import {
57 chat,
58 chatParamsFromRequest,
59 memoryStream,
60 resumeServerSentEventsResponse,
61 toServerSentEventsResponse,
62} from '@tanstack/ai'
63import { openaiText } from '@tanstack/ai-openai'
64import { reconstructChat, withPersistence } from '@tanstack/ai-persistence'
65import { persistence } from './persistence'
66​
67export async function POST(request: Request) {
68 const params = await chatParamsFromRequest(request)
69 const stream = chat({
70 adapter: openaiText('gpt-6.1-sol'),
71 messages: params.messages,
72 threadId: params.threadId,
73 runId: params.runId,
74 ...(params.resume ? { resume: params.resume } : {}),
75 middleware: [withPersistence(persistence)],
76 })
77 return toServerSentEventsResponse(stream, {
78 durability: { adapter: memoryStream(request) },
79 })
81​
82export function GET(request: Request): Response | Promise<Response> {
83 const durability = memoryStream(request)
84 // A reply is still streaming: replay it from the log.
85 if (durability.resumeFrom() !== null) {
86 return resumeServerSentEventsResponse({ adapter: durability })
87 }
88 // Otherwise send back the stored thread.
89 return reconstructChat(persistence, request, {
90 // Without this check, anyone who guesses a thread id can read the thread.
91 authorize: async (threadId, req) => ownsThread(req, threadId),
92 })
94​
95async function ownsThread(request: Request, threadId: string): Promise<boolean> {
96 void request
97 void threadId
98 return true // Replace with your session and ownership check.
100```
101​
102### 4. Turn it on in the client
103​
104Give `useChat` a stable `threadId` and set `persistence: true`:
105​
106```tsx
107import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
108​
109export function Chat() {
110 const { messages, sendMessage } = useChat({
111 threadId: 'support-chat',
112 connection: fetchServerSentEvents('/api/chat'),
113 persistence: true,
114 })
115 return (
116 <div>
117 {messages.map((message) => (
118 <div key={message.id}>{message.role}</div>
119 ))}
120 <button type="button" onClick={() => void sendMessage('hi')}>
121 Send
122 </button>
123 </div>
124 )
126```
127​
128Send a message, then reload the page. The conversation comes back. Reload while a reply streams, and the reply finishes in place.
129​
130> [!TIP]
131> Your coding assistant can do this setup for you. After you install the package, run `npx @tanstack/intent@latest install` to add this package's [Agent Skills](../getting-started/agent-skills). Then ask it to "add chat persistence to this app".
132​
133## Keep the chat in the browser instead
134​
135If you do not want a server store, give `useChat` a browser storage adapter. You do not need steps 1, 2, or 3:
136​
137```tsx
138import {
139 fetchServerSentEvents,
140 localStoragePersistence,
141 useChat,
142} from '@tanstack/ai-react'
143​
144export function Chat() {
145 const { messages } = useChat({
146 threadId: 'support-chat',
147 connection: fetchServerSentEvents('/api/chat'),
148 persistence: localStoragePersistence(),
149 })
150 return <p>{messages.length} messages</p>
152```
153​
154This keeps the chat on one device only. [Client persistence](./client-persistence) compares the two modes and the storage adapters.
155​
156## How it works
157​
158- `withPersistence` saves the transcript, the run status, and any pending approvals to your stores.
159- `persistence: true` tells `useChat` that the server owns the history. On mount, `useChat` calls your `GET` with the `threadId`.
160- `reconstructChat` returns the stored messages. If a run is still streaming, it also returns that run. Then the client replays the run from the durability log.
161- A second device follows the same path, because the `threadId` is the only key.
162​
163Before you go to production, do these two things:
164​
1651. Replace `memoryPersistence()` with an adapter for your database. See [Build your own adapter](./build-your-own-adapter).
1662. Replace `memoryStream` with a log that all your server processes share. See [Resumable streams](../resumable-streams/overview).
167​
168## Which setup do I want?
169​
170| You want | Use |
171| --- | --- |
172| The chat to survive a reload on one device | A browser storage adapter |
173| The same chat on another device, or after a server restart | The quick setup |
174| A reload in the middle of a reply to finish the reply | The quick setup |
175| A dropped connection to resume while the page stays open | [Resumable Streams](../resumable-streams/overview) alone |
176| A human approval that can wait for days | The quick setup with an `interrupts` store. See [Chat persistence](./chat-persistence) |
177| Sandbox files to come back after the provider sandbox is gone | [Keep Files After Reload](../sandbox/portable-snapshots-configure) |
178​
179## Generation and sandboxes
180​
181The same idea works outside chat:
182​
183- **Image, video, speech, and transcription.** The generation hooks take `persistence: true` too. See [Generation persistence](./generation-persistence). To keep the files after the provider links expire, see [Keep generated files](./keep-generated-files).
184- **Sandboxed agents.** A run can outlive the tab, and another host can adopt it. See [Build a Sandbox Adapter](./build-a-sandbox-adapter) for what to store, and [Durable Runs](../sandbox/durable-runs) for the reasons.
185​
186When something surprises you, read [How persistence works](./internals). It explains threads, runs, who owns the history, and the middleware lifecycle.