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

convex-collection.md

344 lines18.9 KB

1---
2title: Convex Collection
3---
4​
5`@tanstack/convex-db-collection` subscribes to a Convex query and keeps its rows in a TanStack DB collection. Use DB for local filters, joins, and optimistic writes. Convex still runs your server functions and handles authentication, reconnects, and access control.
6​
7## Install
8​
9```sh
10npm install @tanstack/convex-db-collection @tanstack/db convex
11```
12​
13## Subscribe to a query
14​
15Use a public Convex query that returns an array of documents. The adapter infers document and argument types from your generated function reference.
16​
17```ts
18import { createCollection } from '@tanstack/db'
19import { convexCollectionOptions } from '@tanstack/convex-db-collection'
20import { ConvexClient } from 'convex/browser'
21import { api } from './convex/_generated/api'
22import type { FunctionReturnType } from 'convex/server'
23​
24type Task = FunctionReturnType<typeof api.tasks.list>[number]
25​
26const client = new ConvexClient('https://your-deployment.convex.cloud')
27​
28export const tasks = createCollection(
29 convexCollectionOptions({
30 id: 'tasks',
31 client,
32 query: api.tasks.list,
33 queryArgs: { projectId },
34 getKey: (task: Task) => task._id,
35 }),
37​
38await tasks.preload()
39```
40​
41An existing `ConvexReactClient`, including the client from `useConvex()`, also works. The adapter imports neither React nor the Convex runtime. Keep the client and collection stable across renders.
42​
43Create fresh adapter options for each direct `createCollection` call. Reusing the same options, including a shallow copy, throws. A `collectionOptions` descriptor can still materialize independent collections in separate `DbClient` instances.
44​
45Each result replaces the subscribed query's rows. Missing documents are deleted, and missing fields are removed. An empty array is a ready, empty collection. Keys must be unique strings or finite numbers. Duplicate keys reject the complete result and preserve the last valid snapshot.
46​
47`convexCollectionOptions` uses eager sync. DB filters, ordering, and limits apply locally to the subscribed result. They do not change your Convex query or fetch documents outside its result. To change the query arguments, create a new collection with a distinct ID.
48​
49## Write through Convex mutations
50​
51Supply handlers for the operations your application supports. Await mutations on the same client used for the subscription.
52​
53```ts
54import { createCollection } from '@tanstack/db'
55import { convexCollectionOptions } from '@tanstack/convex-db-collection'
56​
57const tasks = createCollection(
58 convexCollectionOptions({
59 id: 'tasks',
60 client,
61 query: api.tasks.list,
62 queryArgs: { projectId },
63 getKey: (task: Task) => task._id,
64 onUpdate: async ({ transaction }) => {
65 await Promise.all(
66 transaction.mutations.map(({ original, changes }) =>
67 client.mutation(api.tasks.update, {
68 id: original._id,
69 ...changes,
70 }),
71 ),
72 )
73 },
74 onDelete: async ({ transaction }) => {
75 await Promise.all(
76 transaction.mutations.map(({ original }) =>
77 client.mutation(api.tasks.remove, { id: original._id }),
78 ),
79 )
80 },
81 }),
83​
84const taskId: string = selectedTask._id
85const transaction = tasks.update(taskId, (task) => {
86 task.completed = true
87})
88await transaction.when('settled')
89```
90​
91DB applies optimistic writes immediately. Successful Convex mutation promises wait for the client's queries to catch up. Before a handler settles, the adapter reads the latest cached result and waits for DB to accept its sync writes. It does not wait for visibility held by that same optimistic transaction. If a wrapping persistence layer rejects source acceptance, that sync run stays failed. Call `collection.reload()` before retrying replay. After readiness, a provider query error can recover when a later valid result arrives. A failed first load requires `reload()`. A rejected handler rolls back its optimistic writes.
92​
93Awaiting an HTTP mutation, an action, a different client's mutation, or a detached promise does not provide this query synchronization guarantee. Avoid applying Convex optimistic updates to the same query, because the adapter would receive those local results as source data.
94​
95A DB transaction does not make several Convex calls atomic. For atomic batches, send the complete batch through one Convex mutation. That mutation defines argument validation, authorization, and server write behavior.
96​
97### Inserts and generated IDs
98​
99Convex assigns `_id` on the server. DB needs a stable key before an optimistic insert. For optimistic inserts, add an application key such as `clientId` to your schema and documents. Use that key in `getKey` and send it through your insert mutation. Use `select` to omit server-only fields from the local row type.
100​
101```ts
102convexCollectionOptions({
103 client,
104 query: api.tasks.list,
105 queryArgs: { projectId },
106 select: (tasks) => tasks.map((task) => ({
107 clientId: task.clientId,
108 projectId: task.projectId,
109 title: task.title,
110 })),
111 getKey: (task: { clientId: string; projectId: string; title: string }) => task.clientId,
112 onInsert: async ({ transaction }) => {
113 await Promise.all(
114 transaction.mutations.map(({ modified }) =>
115 client.mutation(api.tasks.create, {
116 clientId: modified.clientId,
117 projectId: modified.projectId,
118 title: modified.title,
119 }),
120 ),
121 )
122 },
123})
124```
125​
126Insert a local row with `tasks.insert({ clientId: crypto.randomUUID(), projectId, title })`. The server query must return the same `clientId`.
127​
128Alternatively, call `client.mutation(api.tasks.create, args)` directly. The subscription adds the resulting document with its server ID. The adapter does not invent Convex IDs or silently replace temporary keys.
129​
130## Project query results
131​
132For an envelope or a nullable document, supply `select`. Its output is the complete set of rows for that collection.
133​
134```ts
135convexCollectionOptions({
136 client,
137 query: api.tasks.listWithMetadata,
138 queryArgs: { projectId },
139 select: (result) => result.tasks,
140 getKey: (task: Task) => task._id,
141})
142​
143convexCollectionOptions({
144 client,
145 query: api.tasks.get,
146 queryArgs: { id: taskId },
147 select: (task) => (task === null ? [] : [task]),
148 getKey: (task: Task) => task._id,
149})
150```
151​
152Keep projections synchronous and treat query results as immutable. A projection can change the row shape. A standard schema can validate local writes through the collection's `schema` option.
153​
154## Complete eager pagination
155​
156Use `convexPaginatedCollectionOptions` for a complete eager mirror of a finite query that returns Convex's `PaginationResult`. The adapter supplies `paginationOpts`, loads every page automatically, and keeps the full result and its page subscriptions in memory. `preload()` waits for the whole result. Set a server-side scope such as a project or workspace before using it with a large table.
157​
158```ts
159import { createCollection } from '@tanstack/db'
160import { convexPaginatedCollectionOptions } from '@tanstack/convex-db-collection'
161​
162const tasks = createCollection(
163 convexPaginatedCollectionOptions({
164 id: 'project-tasks',
165 client,
166 query: api.tasks.paginated,
167 queryArgs: { projectId },
168 pageSize: 100,
169 maxRows: 5_000,
170 getKey: (task: Task) => task._id,
171 }),
173​
174await tasks.preload()
175```
176​
177Your server query must pass `paginationOpts` through to the same ordered Convex database query on every call. Use Convex's `paginationOptsValidator` for argument validation.
178​
179The adapter keeps each loaded cursor range subscribed. Fixed `endCursor` boundaries prevent gaps when rows move or are deleted. Convex split hints replace a range with two subscriptions. The adapter publishes a replacement only after every range is available and the final page reports exhaustion. `preload()` waits for this complete initial result. During later page acquisition, the last complete snapshot stays visible.
180​
181`pageSize` defaults to 100 and must be a positive safe integer. It sets the initial request size. Reactive ranges can contain more rows after inserts. Both supported clients use their public query subscription APIs, without experimental pagination methods.
182​
183`maxRows` defaults to 10,000 and must be a positive safe integer. It caps the accepted complete result. An oversized result rejects with `RangeError` before the adapter publishes it or continues past a known oversized prefix. Initial `preload()` rejects; later growth preserves the last accepted snapshot and reports the error through `onError` and `getSyncError()`. Raise the finite cap only for a source size your application can hold.
184​
185The cap does not limit the bytes in a server response or guarantee peak memory use. A single reactive page can already exceed it. `pageSize` does not bound total memory or initial load time. Initial acquisition can inspect earlier cached pages repeatedly as it extends the cursor chain.
186​
187In eager mode, `select` receives the complete row array. DB applies local filters, joins, ordering, and limits to that mirror.
188​
189## Lazy pagination for a fixed query
190​
191Set `syncMode: 'on-demand'` on the same paginated factory to acquire pages as an ordered DB query needs them. Declare the server query's leading numeric order with `queryOrder`. The server function must always paginate that same query in that direction.
192​
193```ts
194import type { FunctionReference, PaginationOptions, PaginationResult } from 'convex/server'
195​
196type RankedTask = { _id: string; rank: number }
197const paginatedByRank: FunctionReference<
198 'query',
199 'public',
200 { projectId: string; paginationOpts: PaginationOptions },
201 PaginationResult<RankedTask>
202> = api.tasks.paginatedByRank
203​
204const tasks = createCollection(
205 convexPaginatedCollectionOptions({
206 client,
207 query: paginatedByRank,
208 queryArgs: { projectId },
209 syncMode: 'on-demand',
210 queryOrder: { field: 'rank', direction: 'asc' },
211 autoIndex: 'eager',
212 defaultIndexType: BTreeIndex,
213 pageSize: 100,
214 getKey: (task) => task._id,
215 }),
217​
218const window = createLiveQueryCollection((q) =>
219 q.from({ task: tasks })
220 .orderBy(({ task }) => task.rank)
221 .orderBy(({ task }) => task._id)
222 .select(({ task }) => task)
223 .limit(25),
225await window.preload()
226await window.utils.setWindow({ offset: 25, limit: 25 })
227```
228​
229Import `createLiveQueryCollection` and `BTreeIndex` from `@tanstack/db`. The leading DB order must match `queryOrder`; trailing order terms run locally. Each load acquires a contiguous prefix with every row tied at its leading boundary. This may load more rows than the displayed window. Offset windows acquire the preceding prefix too. An unlimited source request, including `tasks.preload()`, loads the whole query. With no demand or a zero limit, no page is started.
230​
231The explicit query type above states the server contract. Convex's generated API normally supplies that type, so an app can pass `api.tasks.paginatedByRank` directly.
232​
233The initial profile supports finite numeric leading fields, aligned ordered windows, core boundary-tie requests, and forward continuations. It rejects other source filters and differently ordered requests. Put application filters in the fixed server query's arguments. `select` on the collection options is unavailable in on-demand mode; use DB query projections as shown above. This API does not translate general DB queries into Convex functions.
234​
235Loaded ranges stay subscribed until collection cleanup. Later inserts, deletes, moves, splits, and reconnects repair the active windows. While more coverage is pending, a public live query retains its last complete window. A successful subset load waits for its accepted writes to become visible, including when optimistic writes hold them. `utils.awaitSync()` waits for source acceptance and remains safe inside mutation handlers.
236​
237`maxRows` also caps the retained lazy prefix. It does not bound requests, network bytes, scans, or peak memory. A boundary tie or a whole-source request can still require the complete query. Use server-side scoping and a suitable finite cap for your application.
238​
239## Durable offline writes
240​
241Use the existing durable outbox with the Convex bridge:
242​
243```sh
244npm install @tanstack/offline-transactions
245```
246​
247Start from a stable Collection that uses an application key such as `clientId`. Keep its ID, registry key, and named mutation function stable across reloads.
248​
249```ts
250import { IndexedDBAdapter, startOfflineExecutor } from '@tanstack/offline-transactions'
251import { convexMutationCodec, convexOfflineMutation } from '@tanstack/convex-db-collection/offline'
252​
253type Task = { clientId: string; title: string; completed: boolean }
254​
255const executor = startOfflineExecutor({
256 mutationCodec: convexMutationCodec,
257 collections: { tasks },
258 storage: new IndexedDBAdapter('project-task-outbox'),
259 mutationFns: {
260 saveTask: convexOfflineMutation({
261 client,
262 mutation: api.tasks.saveIdempotently,
263 collections: [tasks],
264 getArgs: ({ transaction }) => {
265 const task = transaction.mutations[0].modified as Task
266 return { clientId: task.clientId, title: task.title, completed: task.completed }
267 },
268 }),
269 },
270})
271​
272await executor.waitForInit()
273​
274const addTask = executor.createOfflineAction<Task>({
275 mutationFnName: 'saveTask',
276 onMutate: (task) => { tasks.insert(task) },
277})
278​
279const transaction = addTask({
280 clientId: crypto.randomUUID(),
281 title: 'Works after a reload',
282 completed: false,
283})
284​
285void transaction.when('settled').catch(reportError)
286```
287​
288Use the offline action to create durable writes. Calling `tasks.insert()` directly uses its normal handler and does not enter the durable outbox. The example's `tasks` Collection must project the same `Task` shape and use `clientId` as its key.
289​
290The opt-in codec preserves Convex BigInt, binary data, special floats, and undefined fields in mutation changes. Keep the same codec configured across reloads. Missing or incompatible codecs stop replay and retain the stored work. Transaction metadata keeps the outbox’s existing JSON/Date/Temporal behavior.
291​
292The outbox records the transaction before sending it. After a reload, the executor restores pending optimistic writes and replays their named mutation functions. The bridge supplies the original `idempotencyKey`, waits for the Convex mutation, then waits for each configured Collection to accept its source snapshot. It does not wait for visibility held by that same optimistic transaction. If a wrapping persistence layer rejects source acceptance, that sync run stays failed. Call `collection.reload()` before retrying replay. After readiness, a provider query error can recover when a later valid result arrives. A failed first load requires `reload()`.
293​
294Convex handles WebSocket interruptions without rejecting the mutation promise. Argument-construction errors and rejected mutation calls are terminal failures. The bridge turns them into `NonRetriableError`, so the executor rolls back instead of retrying invalid writes indefinitely. A later source-sync failure can retry with the original key.
295​
296### Deduplicate on the server
297​
298Your Convex mutation must accept `idempotencyKey: v.string()`. In that same mutation transaction:
299​
3001. Look up the key in an indexed receipts table.
3012. If a receipt exists, return its saved result.
3023. Apply the complete write or batch.
3034. Store the key and result in the receipts table.
304​
305Convex executes these writes atomically. A client can lose an acknowledgement after the server commits, so SDK request deduplication alone cannot replace this durable receipt. Keep receipts for at least the full replay lifetime. Scope receipt keys to the authenticated owner, and apply authorization before returning a saved result.
306​
307The [real backend test fixture](https://github.com/TanStack/db/blob/main/packages/convex-db-collection/e2e/backend/convex/tasks.ts) shows an idempotent write mutation. It is an isolated test backend without application authorization, so add your own access checks.
308​
309For atomic batches, `getArgs` must include every operation in the offline transaction and your server mutation must apply them together. The example handles one insert per action. Supply the platform's storage and coordination adapters when using the executor outside a browser. See the [offline transactions guide](../guides/offline-transactions.md) for leadership, storage failures, retry policy, and disposal.
310​
311The outbox stores pending writes, not a full offline read cache. Pair the Collection with DB's persistence support when it must show previously synced rows after a reload without network access.
312​
313## Errors and cleanup
314​
315```ts
316convexCollectionOptions({
317 client,
318 query: api.tasks.list,
319 queryArgs: { projectId },
320 getKey: (task: Task) => task._id,
321 onError: (error) => reportError(error),
322})
323```
324​
325An initial subscription or projection error rejects `preload()` with the original error and ends that sync run. Call `collection.reload()` to try again. Later recoverable errors preserve existing rows, set `collection.health.failureReason`, and call `onError`. A valid query result clears that failure reason. `collection.utils.getSyncError()` returns the latest error, but this getter is not reactive. A rejected source acceptance stops the run and sets its health error; it also requires `reload()`.
326​
327Collection cleanup rejects while live queries or Effects read it. Unmount those consumers first, or use `collection.cleanup({ dependents: true })`. Cleanup unsubscribes and invalidates callbacks from that sync run. It does not close the shared Convex client. After a restart, the first result replaces retained data, including when the result is empty. Close the client separately when your application no longer needs it.
328​
329## Scope
330​
331This adapter uses the supported `onUpdate` and `watchQuery` APIs, tested with Convex 1.47.0 and a real isolated local Convex backend. It does not access private client fields or implement a second Convex protocol.
332​
333Convex only exposes data through your server functions. The adapter cannot bypass authorization, subscribe directly to an arbitrary table, or translate arbitrary DB predicates into Convex functions. Queries remain subject to Convex read and result limits. A paginated query result describes one page, not a complete table. Automatic reactive pagination uses `convexPaginatedCollectionOptions`. Arbitrary server predicate pushdown is not implemented.
334​
335Convex manages connection recovery. Use the offline bridge for durable writes. A full read cache and an SSR snapshot fetch remain separate concerns. Reuse your existing Convex authentication setup. For SSR, use request-scoped `DbClient` instances and the DB hydration APIs. A module-scoped descriptor can wrap `convexCollectionOptions` with `collectionOptions`; each client receives fresh adapter state. Supply an appropriate Convex client for each request and close it when finished.
336​
337## Run the backend tests
338​
339```sh
340pnpm --filter @tanstack/convex-db-collection... build
341pnpm --filter @tanstack/convex-db-collection test:e2e
342```
343​
344The test command starts an anonymous local Convex backend, deploys the fixture, runs both client integrations and generated process-crash histories, then stops the backend. It needs network access on the first run to download Convex's backend binary. It does not use your cloud deployment or deploy key.