Skip to main content

RxDB Quickstart

Welcome to the RxDB Quickstart. Here we'll learn how to create a simple real-time app with the RxDB database that is able to store and query data persistently in a browser and does realtime updates to the UI on changes.


JavaScript Embedded Database

1

Installation​

Install the RxDB library and the RxJS dependency:

npm install rxdb rxjs
2

Pick a Storage​

RxDB is able to run in a wide range of JavaScript runtimes like browsers, mobile apps, desktop and servers. Therefore different storage engines exist that ensure the best performance depending on where RxDB is used.

Use this for the simplest browser setup and very small datasets. It has a tiny bundle size and works anywhere localStorage is available, but is not optimized for large data or heavy writes.

import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage';

let storage = getRxStorageLocalstorage();
Which storage should I use?

RxDB provides a wide range of storages depending on your JavaScript runtime and performance needs.

3

Dev-Mode​

When you use RxDB in development, you should always enable the dev-mode plugin, which adds helpful checks and validations, and tells you if you do something wrong.

import { addRxPlugin } from 'rxdb/plugins/core';
import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode';

addRxPlugin(RxDBDevModePlugin);
4

Schema Validation​

Schema validation is required when using dev-mode and recommended (but optional) in production. Wrap your storage with the AJV schema validator to ensure all documents match your schema before being saved.

import { wrappedValidateAjvStorage } from 'rxdb/plugins/validate-ajv';

storage = wrappedValidateAjvStorage({ storage });
5

Create a Database​

A database is the top‑level container in RxDB, responsible for managing collections, coordinating persistence, and providing reactive change streams.

import { createRxDatabase } from 'rxdb/plugins/core';

const myDatabase = await createRxDatabase({
name: 'mydatabase',
storage: storage
});
6

Add a Collection​

An RxDatabase contains RxCollections for storing and querying data. A collection is similar to an SQL table, and individual records are stored in the collection as JSON documents. An RxDatabase can have as many collections as you need. Add a collection with a schema to the database:

await myDatabase.addCollections({
// name of the collection
todos: {
// we use the JSON-schema standard
schema: {
version: 0,
primaryKey: 'id',
type: 'object',
properties: {
id: {
type: 'string',
maxLength: 100 // <- the primary key must have maxLength
},
name: {
type: 'string'
},
done: {
type: 'boolean'
},
timestamp: {
type: 'string',
format: 'date-time'
}
},
required: ['id', 'name', 'done', 'timestamp']
}
}
});
7

Insert a document​

Now that we have an RxCollection we can store some documents in it.

const myDocument = await myDatabase.todos.insert({
id: 'todo1',
name: 'Learn RxDB',
done: false,
timestamp: new Date().toISOString()
});
8

Run a Query​

Execute a query that returns all found documents once:

const foundDocuments = await myDatabase.todos.find({
selector: {
done: {
$eq: false
}
}
}).exec();
9

Update a Document​

In the first found document, set done to true:

const firstDocument = foundDocuments[0];
await firstDocument.patch({
done: true
});
10

Delete a document​

Delete the document so that it can no longer be found in queries:

await firstDocument.remove();
11

Observe a Query​

Subscribe to data changes so that your UI is always up-to-date with the data stored on disk. RxDB allows you to subscribe to data changes even when the change happens in another part of your application, another browser tab, or during database replication/synchronization:

const observable = myDatabase.todos.find({
selector: {
done: {
$eq: false
}
}
}).$ // get the observable via RxQuery.$;
observable.subscribe(notDoneDocs => {
console.log('Currently have ' + notDoneDocs.length + ' things to do');
// -> here you would re-render your app to show the updated document list
});
12

Observe a Document value​

You can also subscribe to the fields of a single RxDocument. Add the $ sign to the desired field and then subscribe to the returned observable.

myDocument.done$.subscribe(isDone => {
console.log('done: ' + isDone);
});
13

Sync the Client​

RxDB has multiple replication plugins to replicate database state with a server.

The easiest way to replicate data between your clients' devices is the WebRTC replication plugin that replicates data between devices without a centralized server. This makes it easy to try out replication without having to host anything:

import {
replicateWebRTC,
getConnectionHandlerSimplePeer
} from 'rxdb/plugins/replication-webrtc';
replicateWebRTC({
collection: myDatabase.todos,
connectionHandlerCreator: getConnectionHandlerSimplePeer({}),
topic: '', // <- set any app-specific room id here.
secret: 'mysecret',
pull: {},
push: {}
})

Next steps​

You are now ready to dive deeper into RxDB.

  • Start reading the full documentation here.
  • There is a full implementation of the quickstart guide so you can clone that repository and play with the code.
  • For frameworks and runtimes like Angular, React Native and others, check out the list of example implementations.
  • Also please continue reading the documentation, join the community on our Discord chat, and star the GitHub repo.
  • If you are using RxDB in a production environment and are able to support its continued development, please take a look at the πŸ‘‘ Premium package which includes additional plugins and utilities.
βœ•