RxDB

A fast, offline-first, reactive database for JavaScript Applications

README

<!--
| Announcement                                                        |
| :--: |
| Please take part in the RxDB user survey 2022. This will help me to better plan the steps for the next major release. (takes about 2 minutes)
-->



A fast, offline-first, reactive Database for JavaScript Applications

     
     
     
     

    
     

  What is RxDB?

RxDB (short for Reactive Database) is an offline-first, NoSQL-database for JavaScript Applications like Websites, hybrid Apps, Electron-Apps, Progressive Web Apps and Node.js. Reactive means that you can not only query the current state, but subscribe to all state changes like the result of a query or even a single field of a document. This is great for UI-based realtime applications in a way that makes it easy to develop and also has great performance benefits but can also be used to create fast backends in Node.js.
RxDB provides an easy to implement protocol for realtime replication with your existing infrastructure or any compliant CouchDB endpoint.
RxDB is based on a storage interface that enables you to swap out the underlying storage engine. This increases code reuse because you can use the same database code for different JavaScript environments by just switching out the storage settings.


Use the quickstart, read the documentation or explore the example projects.

  Multiplayer realtime applications




realtime.gif


  Replicate with your existing infrastructure


RxDB provides an easy to implement, battle-tested replication protocol for realtime sync with your existing infrastructure.
There are also plugins to replicate with any CouchDB endpoint or over GraphQL and REST or even P2P.



  Flexible storage layer


RxDB is based on a storage interface that enables you to swap out the underlying storage engine. This increasescode reuse because the same database code can be used in different JavaScript environments by just switching out the storage settings.

You can use RxDB on top of IndexedDB, PouchDB, LokiJS, Dexie.js, in-memory, SQLite, in a WebWorker thread and even on top of FoundationDB.

No matter what kind of runtime you have, as long as it runs JavaScript, it can run RxDB:

Browsers Node.js Electron React Native
  Cordova/Phonegap
  Capacitor
NativeScript Flutter

  Quick start



Install


  1. ```sh
  2. npm install rxdb rxjs --save
  3. ```

Store data


  1. ``` js
  2. import {
  3.   createRxDatabase
  4. } from 'rxdb';

  5. /**
  6. * For browsers, we use the dexie.js based storage
  7. * which stores data in IndexedDB.
  8. * In other JavaScript runtimes, we can use different storages.
  9. * @link https://rxdb.info/rx-storage.html
  10. */
  11. import { getRxStorageDexie } from 'rxdb/plugins/dexie';

  12. // create a database
  13. const db = await createRxDatabase({
  14.     name: 'heroesdb', // the name of the database
  15.     storage: getRxStorageDexie()
  16. });

  17. // add collections
  18. await db.addCollections({
  19.   heroes: {
  20.     schema: mySchema
  21.   }
  22. });

  23. // insert a document
  24. await db.heroes.insert({
  25.   name: 'Bob',
  26.   healthpoints: 100
  27. });
  28. ```

Query data once

  1. ``` js
  2. const aliveHeroes = await db.heroes.find({
  3.   selector: {
  4.     healthpoints: {
  5.       $gt: 0
  6.     }
  7.   }
  8. }).exec(); // the exec() returns the result once
  9. ```

Observe a Query

  1. ``` js
  2. await db.heroes.find({
  3.   selector: {
  4.     healthpoints: {
  5.       $gt: 0
  6.     }
  7.   }
  8. })
  9. .$ // the $ returns an observable that emits each time the result set of the query changes
  10. .subscribe(aliveHeroes => console.dir(aliveHeroes));
  11. ```



Continue with the quickstart here.



  More Features (click to toggle)

Subscribe to events, query results, documents and event single fields of a document


RxDB implements rxjs to make your data reactive.
This makes it easy to always show the real-time database-state in the dom without manually re-submitting your queries.


  1. ``` js
  2. db.heroes
  3.   .find()
  4.   .sort('name')
  5.   .$ // <- returns observable of query
  6.   .subscribe( docs => {
  7.     myDomElement.innerHTML = docs
  8.       .map(doc => '<li>' + doc.name + '</li>')
  9.       .join();
  10.   });
  11. ```

reactive.gif

MultiWindow/Tab


RxDB supports multi tab/window usage out of the box. When data is changed at one browser tab/window or Node.js process, the change will automatically be broadcasted to all other tabs so that they can update the UI properly.


multiwindow.gif

EventReduce

One big benefit of having a realtime database is that big performance optimizations can be done when the database knows a query is observed and the updated results are needed continuously. RxDB internally uses the Event-Reduce algorithm. This makes sure that when you update/insert/remove documents,

    the query does not have to re-run over the whole database but the new results will be calculated from the events. This creates a huge performance-gain
    with zero cost.


Use-Case-Example


Imagine you have a very big collection with many user-documents. At your page you want to display a toplist with users which have the most points and are currently logged in.
You create a query and subscribe to it.

  1. ``` js
  2. const query = usersCollection.find().where('loggedIn').eq(true).sort('points');
  3. query.$.subscribe(users => {
  4.     document.querySelector('body').innerHTML = users
  5.         .reduce((prev, cur) => prev + cur.username+ '<br/>', '');
  6. });
  7. ```

As you may detect, the query can take very long time to run, because you have thousands of users in the collection.
When a user now logs off, the whole query will re-run over the database which takes again very long.

  1. ``` js
  2. await anyUser.atomicPatch({loggedIn: false});
  3. ```

But not with the EventReduce.
Now, when one user logs off, it will calculate the new results from the current results plus the RxChangeEvent. This often can be done in-memory without making IO-requests to the storage-engine. EventReduce not only works on subscribed queries, but also when you do multiple .exec()'s on the same query.

Schema


Schemas are defined via [jsonschema](http://json-schema.org/) and are used to describe your data.


  1. ``` js
  2. const mySchema = {
  3.     title: "hero schema",
  4.     version: 0,                 // <- incremental version-number
  5.     description: "describes a simple hero",
  6.     primaryKey: 'name',         // <- 'name' is the primary key for the coollection, it must be unique, required and of the type string
  7.     type: "object",
  8.     properties: {
  9.         name: {
  10.             type: "string",
  11.             maxLength: 30
  12.         },
  13.         secret: {
  14.             type: "string",
  15.         },
  16.         skills: {
  17.             type: "array",
  18.             maxItems: 5,
  19.             uniqueItems: true,
  20.             item: {
  21.                 type: "object",
  22.                 properties: {
  23.                     name: {
  24.                         type: "string"
  25.                     },
  26.                     damage: {
  27.                         type: "number"
  28.                     }
  29.                 }
  30.             }
  31.         }
  32.     },
  33.     required: ["color"],
  34.     encrypted: ["secret"] // <- this means that the value of this field is stored encrypted
  35. };
  36. ```

Mango / Chained queries

RxDB can be queried by standard NoSQL mango queries like you maybe know from other NoSQL Databases like mongoDB.


Also you can use the query-builder plugin to create chained mango-queries.


  1. ``` js

  2. // normal query
  3. myCollection.find({
  4.   selector: {
  5.     name: {
  6.       $ne: 'Alice'
  7.     },
  8.     age: {
  9.       $gt: 67
  10.     }
  11.   },
  12.   sort: [{ age: 'desc' }],
  13.   limit: 10
  14. })

  15. // chained query
  16. myCollection
  17.   .find()
  18.   .where('name').ne('Alice')
  19.   .where('age').gt(18).lt(67)
  20.   .limit(10)
  21.   .sort('-age')
  22.   .exec().then( docs => {
  23.     console.dir(docs);
  24.   });
  25. ```

Encryption


By setting a schema-field to `encrypted`, the value of this field will be stored in encryption-mode and can't be read without the password. Of course you can also encrypt nested objects. Example:


  1. ``` json
  2. {
  3.   "title": "my schema",
  4.   "properties": {
  5.     "secret": {
  6.       "type": "string",
  7.       "encrypted": true
  8.     }
  9.   },
  10.   "encrypted": [
  11.     "secret"
  12.   ]
  13. }
  14. ```

Import / Export


RxDB lets you import and export the whole database or single collections into json-objects. This is helpful to trace bugs in your application or to move to a given state in your tests.


  1. ``` js
  2. // export a single collection
  3. const jsonCol = await myCollection.dump();

  4. // export the whole database
  5. const jsonDB = await myDatabase.dump();

  6. // import the dump to the collection
  7. await emptyCollection.importDump(json);


  8. // import the dump to the database
  9. await emptyDatabase.importDump(json);
  10. ```

Key-Compression


Depending on which adapter and in which environment you use RxDB, client-side storage is [limited](https://pouchdb.com/2014/10/26/10-things-i-learned-from-reading-and-writing-the-pouchdb-source.html) in some way or the other. To save disc-space, RxDB uses a schema based [keycompression](https://github.com/pubkey/jsonschema-key-compression) to minimize the size of saved documents. This saves about 40% of used storage.


Example:

  1. ``` js
  2. // when you save an object with big keys
  3. await myCollection.insert({
  4.   firstName: 'foo'
  5.   lastName:  'bar'
  6.   stupidLongKey: 5
  7. });

  8. // key compression will internally transform it to
  9. {
  10.   '|a': 'foo'
  11.   '|b':  'bar'
  12.   '|c': 5
  13. }

  14. // so instead of 46 chars, the compressed-version has only 28
  15. // the compression works internally, so you can of course still access values via the original key.names and run normal queries.
  16. console.log(myDoc.firstName);
  17. // 'foo'
  18. ```


And for any other use case, there are many more plugins and addons.


  Get started



Get started now by reading the docs or exploring the example-projects.


  Support and Contribute