Open History to see the last commit
1---
2title: RxDB Collection
3---
4
5# RxDB Collection
6
7RxDB 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.
8
9
10## Overview
11
12The `@tanstack/rxdb-db-collection` package allows you to create collections that:
13- Automatically mirror the state of an underlying RxDB collection
14- Reactively update when RxDB documents change
15- Support optimistic mutations with rollback on error
16- Provide persistence handlers to keep RxDB in sync with TanStack DB transactions
17- Sync across browser tabs - changes in one tab are reflected in RxDB and TanStack DB collections in all tabs
18- Use one of RxDB's [storage engines](https://rxdb.info/rx-storage.html).
19- Work with RxDB's [replication features](https://rxdb.info/replication.html) for offline-first and sync scenarios
20- Leverage RxDB's [replication plugins](https://rxdb.info/replication.html) to sync with CouchDB, MongoDB, Supabase, REST APIs, GraphQL, WebRTC (P2P) and more.
21
22
23### 1. Installation
24
25Install the RxDB collection packages along with your preferred framework integration.
26
27```bash
28npm install @tanstack/rxdb-db-collection rxdb @tanstack/react-db
29```
30
31
32### 2. Create an RxDatabase and RxCollection
33
34```ts
35import { createRxDatabase, addRxPlugin } from 'rxdb/plugins/core'
36
37/**
38 * Here we use the localStorage based storage for RxDB.
39 * RxDB has a wide range of storages based on Dexie.js, IndexedDB, SQLite, and more.
40 */
41import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage'
42
43// add json-schema validation (optional)
44import { wrappedValidateAjvStorage } from 'rxdb/plugins/validate-ajv';
45
46// Enable dev mode (optional, recommended during development)
47import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode'
48addRxPlugin(RxDBDevModePlugin)
49
50type Todo = { id: string; text: string; completed: boolean }
51
52const db = await createRxDatabase({
53 name: 'my-todos',
54 storage: wrappedValidateAjvStorage({
55 storage: getRxStorageLocalstorage()
56 })
57})
58
59await db.addCollections({
60 todos: {
61 schema: {
62 title: 'todos',
63 version: 0,
64 type: 'object',
65 primaryKey: 'id',
66 properties: {
67 id: { type: 'string', maxLength: 100 },
68 text: { type: 'string' },
69 completed: { type: 'boolean' },
70 },
71 required: ['id', 'text', 'completed'],
72 },
73 },
74})
75```
76
77
78### 3. (optional) sync with a backend
79```ts
80import { replicateRxCollection } from 'rxdb/plugins/replication'
81const replicationState = replicateRxCollection({
82 collection: db.todos,
83 pull: { handler: myPullHandler },
84 push: { handler: myPushHandler },
85})
86```
87
88### 4. Wrap the RxDB collection with TanStack DB
89
90```ts
91import { createCollection } from '@tanstack/react-db'
92import { rxdbCollectionOptions } from '@tanstack/rxdb-db-collection'
93
94const todosCollection = createCollection(
95 rxdbCollectionOptions({
96 rxCollection: db.todos,
97 startSync: true, // start ingesting RxDB data immediately
98 })
99)
100```
101
102
103Now `todosCollection` is a reactive TanStack DB collection driven by RxDB:
104
105- Writes via `todosCollection.insert/update/delete` persist to RxDB.
106- Direct writes in RxDB (or via replication) flow into the TanStack collection via change streams.
107
108
109
110## Configuration Options
111
112The `rxdbCollectionOptions` function accepts the following options:
113
114### Required
115
116- `rxCollection`: The underlying [RxDB collection](https://rxdb.info/rx-collection.html)
117
118### Optional
119
120- `id`: Unique identifier for the collection
121- `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.
122- `startSync`: Whether to start syncing immediately (default: true)
123- `onInsert, onUpdate, onDelete`: Override default persistence handlers. By default, TanStack DB writes are persisted to RxDB using bulkUpsert, patch, and bulkRemove.
124- `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.
125
126
127
128## Syncing with Backends
129
130Replication 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.).
131
132When 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.
133
134This 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.
135
136
137## FAQ
138
139### Do I still need RxDB schema indexes if I only query TanStack DB?
140
141Usually 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:
142- You run queries directly against RxDB (e.g. `rxCollection.find(...)`).
143- Your replication setup uses filtered queries or selectors.
144- You rely on RxDB to selectively load subsets of data instead of hydrating everything into memory.
145
146### Is data duplicated between RxDB and TanStack DB?
147
148Yes, 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.
149
150### How does backend ↔ RxDB ↔ TanStack DB synchronization work?
151
152Synchronization follows a clear separation of responsibilities between RxDB and TanStack DB.
153
154**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.
155
156**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.
157
158This design intentionally forms two independent loops:
159- A durability and sync loop managed entirely by RxDB (backend to RxDB).
160- A reactive UI loop managed by TanStack DB (RxDB change stream to in-memory collections to live queries).
161
162## Learn More
163
164- [RxDB Documentation](https://rxdb.info/overview.html)
165- [RxDB Sync Engine](https://rxdb.info/replication.html)
166- [Tanstack DB Live Queries](https://tanstack.com/db/latest/docs/guides/live-queries)
167