Open History to see the last commit
1---
2title: Quickstart
3id: memory-quickstart
4order: 2
5description: "Add memory to a TanStack AI chat route: install the package, create an adapter, add memoryMiddleware with a server-side scope, then move to Redis for production."
6keywords:
7 - tanstack ai
8 - memory
9 - quickstart
10 - in-memory adapter
11 - redis adapter
12 - chat middleware
13---
14
15Add `memoryMiddleware` to a working chat route. The route recalls memory before each answer and saves each turn.
16
17## Quick setup
18
19### 1. Install the package
20
21<!-- ::start:tabs variant="package-manager" mode="install" -->
22
23react: @tanstack/ai-memory
24vue: @tanstack/ai-memory
25solid: @tanstack/ai-memory
26svelte: @tanstack/ai-memory
27preact: @tanstack/ai-memory
28angular: @tanstack/ai-memory
29vanilla: @tanstack/ai-memory
30octane: @tanstack/ai-memory
31
32<!-- ::end:tabs -->
33
34### 2. Create the memory adapter
35
36Start with `inMemory()`. It keeps records in a `Map` in the server process:
37
38```ts
39// memory.ts
40import { inMemory } from '@tanstack/ai-memory/in-memory'
41
42export const memory = inMemory()
43```
44
45### 3. Add the middleware to the server route
46
47Set the scope from your auth session. The `onRecall` log lets you see memory work:
48
49```ts
50// api/chat.ts
51import {
52 chat,
53 chatParamsFromRequest,
54 toServerSentEventsResponse,
55} from '@tanstack/ai'
56import { openaiText } from '@tanstack/ai-openai'
57import { memoryMiddleware } from '@tanstack/ai-memory'
58import { memory } from './memory'
59
60// Replace with your auth. Read the user from the session, never from the body.
61function getUserId(_request: Request): string {
62 return 'demo-user'
63}
64
65export async function POST(request: Request) {
66 const params = await chatParamsFromRequest(request)
67 const userId = getUserId(request)
68
69 const stream = chat({
70 adapter: openaiText('gpt-6.1-sol'),
71 messages: params.messages,
72 threadId: params.threadId,
73 middleware: [
74 memoryMiddleware({
75 adapter: memory,
76 // In a real app, make sure that this thread belongs to userId.
77 scope: { threadId: params.threadId, userId },
78 onRecall: ({ result }) => {
79 console.log('memory recalled', result.fragments?.length ?? 0, 'items')
80 },
81 }),
82 ],
83 })
84 return toServerSentEventsResponse(stream)
85}
86```
87
88### 4. Use the chat in the client
89
90Memory runs on the server only. The client is a normal chat client:
91
92```tsx
93import { useState } from 'react'
94import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
95
96export function Chat() {
97 const [input, setInput] = useState('')
98 const { messages, sendMessage } = useChat({
99 connection: fetchServerSentEvents('/api/chat'),
100 threadId: 'support-chat',
101 })
102
103 return (
104 <>
105 {messages.map((message) => (
106 <div key={message.id}>
107 {message.parts.map((part, index) =>
108 part.type === 'text' ? <p key={index}>{part.content}</p> : null,
109 )}
110 </div>
111 ))}
112 <form
113 onSubmit={(event) => {
114 event.preventDefault()
115 void sendMessage(input)
116 setInput('')
117 }}
118 >
119 <input value={input} onChange={(event) => setInput(event.target.value)} />
120 <button type="submit">Send</button>
121 </form>
122 </>
123 )
124}
125```
126
127For Vue, Solid, Svelte, and the other frameworks, use the client from the [Quick Start](../getting-started/quick-start). Nothing in it changes for memory.
128
129### 5. Try it
130
1311. Send `My favorite language is TypeScript`.
1322. Send `Which language do I like?`.
133
134The server log shows `memory recalled 2 items` (or a similar count) for the second message. The first turn was saved and then recalled into the prompt.
135
136## How it works
137
138- Before the model runs, the adapter finds records in the same scope that match the last user message. They go into the system prompt.
139- After the stream finishes, the adapter saves the user message and the assistant answer.
140- `inMemory()` scores by word overlap and recency. Records are lost when the process restarts.
141
142## Move to production
143
144### Use Redis
145
146`redis()` keeps memory across restarts and shares it between server processes. Change only `memory.ts`. The route stays the same:
147
148```ts
149// memory.ts
150import Redis from 'ioredis'
151import { redis } from '@tanstack/ai-memory/redis'
152
153const client = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379')
154
155export const memory = redis({ redis: client })
156```
157
158Install `ioredis` (or `redis`) yourself. Both are optional peer dependencies. For `node-redis` and the other options, see [`redis()`](./adapters#redis).
159
160To use a hosted service, export `hindsight()`, `mem0()`, or `honcho()` from `memory.ts` instead. See [Adapters](./adapters).
161
162### Add semantic scoring (optional)
163
164Word overlap misses a question that uses different words than the stored text. Add an `embedder` to `inMemory()` or `redis()` to also score by meaning:
165
166```ts
167// memory.ts
168import OpenAI from 'openai'
169import { inMemory } from '@tanstack/ai-memory/in-memory'
170
171const openai = new OpenAI()
172
173export const memory = inMemory({
174 embedder: {
175 async embed(text) {
176 const result = await openai.embeddings.create({
177 model: 'text-embedding-3-small',
178 input: text,
179 })
180 const embedding = result.data[0]?.embedding
181 if (!embedding) throw new Error('embedding request returned no vector')
182 return embedding
183 },
184 },
185})
186```
187
188The embedder runs on each recall (for the query) and on each save (for the stored text).
189
190Your route now remembers what the user says and can move to Redis with a one-file change. To log memory in production and watch it in devtools, see [Operating memory](./operating).