Open History to see the last commit
1---
2title: RxDB Collection
3---
4
5RxDB collections provide seamless integration between TanStack DB and [RxDB](https://rxdb.info), enabling automatic synchronization between your in-memory TanStack DB collections and RxDB's local-first database. Giving you offline-ready persistence, and powerful sync capabilities with a wide range of backends.
6
7
8## Overview
9
10The `@tanstack/rxdb-db-collection` package allows you to create collections that:
11- Automatically mirror the state of an underlying RxDB collection
12- Reactively update when RxDB documents change
13- Support optimistic mutations with rollback on error
14- Provide persistence handlers to keep RxDB in sync with TanStack DB transactions
15- Sync across browser tabs - changes in one tab are reflected in RxDB and TanStack DB collections in all tabs
16- Use one of RxDB's [storage engines](https://rxdb.info/rx-storage.html).
17- Work with RxDB's [replication features](https://rxdb.info/replication.html) for offline-first and sync scenarios
18- Leverage RxDB's [replication plugins](https://rxdb.info/replication.html) to sync with CouchDB, MongoDB, Supabase, REST APIs, GraphQL, WebRTC (P2P) and more.
19
20
21### 1. Installation
22
23Install the RxDB collection packages along with your preferred framework integration.
24
25```bash
26npm install @tanstack/rxdb-db-collection rxdb @tanstack/react-db
27```
28
29
30### 2. Create an RxDatabase and RxCollection
31
32```ts
33import { createRxDatabase, addRxPlugin } from 'rxdb/plugins/core'
34
35/**
36 * Here we use the localStorage based storage for RxDB.
37 * RxDB has a wide range of storages based on Dexie.js, IndexedDB, SQLite, and more.
38 */
39import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'
40
41// add json-schema validation (optional)
42import { wrappedValidateAjvStorage } from 'rxdb/plugins/validate-ajv';
43
44// Enable dev mode (optional, recommended during development)
45import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode'
46addRxPlugin(RxDBDevModePlugin)
47
48type Todo = { id: string; text: string; completed: boolean }
49
50const db = await createRxDatabase({
51 name: 'my-todos',
52 storage: wrappedValidateAjvStorage({
53 storage: getRxStorageLocalstorage()
54 })
55})
56
57await db.addCollections({
58 todos: {
59 schema: {
60 title: 'todos',
61 version: 0,
62 type: 'object',
63 primaryKey: 'id',
64 properties: {
65 id: { type: 'string', maxLength: 100 },
66 text: { type: 'string' },
67 completed: { type: 'boolean' },
68 },
69 required: ['id', 'text', 'completed'],
70 },
71 },
72})
73```
74
75
76### 3. (optional) sync with a backend
77```ts
78import { replicateRxCollection } from 'rxdb/plugins/replication'
79const replicationState = replicateRxCollection({
80 collection: db.todos,
81 pull: { handler: myPullHandler },
82 push: { handler: myPushHandler },
83})
84```
85
86### 4. Wrap the RxDB collection with TanStack DB
87
88```ts
89import { createCollection } from '@tanstack/react-db'
90import { rxdbCollectionOptions } from '@tanstack/rxdb-db-collection'
91
92const todosCollection = createCollection(
93 rxdbCollectionOptions({
94 rxCollection: db.todos,
95 startSync: true, // start ingesting RxDB data immediately
96 })
97)
98```
99
100
101Now `todosCollection` is a reactive TanStack DB collection driven by RxDB:
102
103- Writes via `todosCollection.insert/update/delete` persist to RxDB.
104- Direct writes in RxDB (or via replication) flow into the TanStack collection via change streams.
105
106
107
108## Configuration Options
109
110The `rxdbCollectionOptions` function accepts the following options:
111
112### Required
113
114- `rxCollection`: The underlying [RxDB collection](https://rxdb.info/rx-collection.html)
115
116### Optional
117
118- `id`: Unique identifier for the collection
119- `schema`: Schema for validating items. RxDB already has schema validation but having additional validation on the TanStack DB side can help to unify error handling between different TanStack collections.
120- `startSync`: Whether to start syncing immediately (default: true)
121- `onInsert, onUpdate, onDelete`: Override default persistence handlers. By default, TanStack DB writes are persisted to RxDB using bulkUpsert, patch, and bulkRemove.
122- `syncBatchSize`: The maximum number of documents fetched per batch during the initial sync from RxDB into TanStack DB (default: 1000). Larger values reduce round trips but use more memory; smaller values are lighter but may increase query calls. Note that this only affects the initial sync. Ongoing live updates are streamed one by one via RxDB's change feed.
123
124
125
126## Syncing with Backends
127
128Replication and sync in RxDB run independently of TanStack DB. You set up replication directly on your RxCollection using RxDB's replication plugins (for CouchDB, GraphQL, WebRTC, REST APIs, etc.).
129
130When replication runs, it pulls and pushes changes to the backend and applies them to the RxDB collection. Since the TanStack DB integration subscribes to the RxDB change stream, any changes applied by replication are automatically reflected in your TanStack DB collection.
131
132This separation of concerns means you configure replication entirely in RxDB, and TanStack DB automatically benefits: your TanStack collections always stay up to date with whatever sync strategy you choose.
133
134
135## FAQ
136
137### Do I still need RxDB schema indexes if I only query TanStack DB?
138
139Usually not, at least for TanStack DB queries themselves. TanStack DB queries run entirely in memory, so RxDB schema indexes do not affect the performance of TanStack DB's live queries. However, RxDB indexes may still be important if:
140- You run queries directly against RxDB (e.g. `rxCollection.find(...)`).
141- Your replication setup uses filtered queries or selectors.
142- You rely on RxDB to selectively load subsets of data instead of hydrating everything into memory.
143
144### Is data duplicated between RxDB and TanStack DB?
145
146Yes, intentionally. RxDB stores data durably on disk. TanStack DB stores data in memory for fast queries and reactivity. This duplication enables high-performance UI queries while retaining [local-first](https://rxdb.info/articles/local-first-future.html) persistence and sync.
147
148### How does backend ↔ RxDB ↔ TanStack DB synchronization work?
149
150Synchronization follows a clear separation of responsibilities between RxDB and TanStack DB.
151
152**RxDB** is responsible for persistence and networking. It stores data durably using a local storage engine (IndexedDB, SQLite, etc.) and handles all replication logic. Replication is configured directly on the RxDB collection and runs independently of TanStack DB. RxDB pulls changes from the backend, applies them locally, resolves conflicts, and pushes local changes back to the backend.
153
154**TanStack DB** sits on top as an in-memory, reactive query layer. It does not talk to the backend directly and does not participate in replication. Instead, it mirrors the current state of the RxDB collection in memory and provides fast live queries and optimistic mutations for the UI.
155
156This design intentionally forms two independent loops:
157- A durability and sync loop managed entirely by RxDB (backend to RxDB).
158- A reactive UI loop managed by TanStack DB (RxDB change stream to in-memory collections to live queries).
159
160## Learn More
161
162- [RxDB Documentation](https://rxdb.info/overview.html)
163- [RxDB Sync Engine](https://rxdb.info/replication.html)
164- [Tanstack DB Live Queries](https://tanstack.com/db/latest/docs/guides/live-queries)
165