RxStorage LocalStorage
RxDB can persist data in various ways. One of the simplest methods is using the browserβs built-in LocalStorage. This storage engine allows you to store and retrieve RxDB documents directly from the browser without needing additional plugins or libraries.
Recommended Default for using RxDB in the Browser
We highly recommend using LocalStorage for a quick and easy RxDB setup, especially when you want a minimal project configuration. For professional projects, the IndexedDB RxStorage is recommended in most cases.
Key Benefitsβ
- Simplicity: No complicated configurations or external dependencies - LocalStorage is already built into the browser.
- Fast for small Datasets: Writing and Reading small sets of data from localStorage is really fast as shown in these benchmarks.
- Ease of Setup: Just import the plugin, import it, and pass
getRxStorageLocalstorage()
intocreateRxDatabase()
. Thatβs it!
Limitationsβ
While LocalStorage is the easiest way to get started, it does come with some constraints:
- Limited Storage Capacity: Browsers often limit LocalStorage to around 5 MB per domain, though exact limits vary.
- Synchronous Access: LocalStorage operations block the main thread. This is usually fine for small amounts of data but can cause performance bottlenecks with heavier use.
Despite these limitations, LocalStorage remains a great default option for smaller projects, prototypes, or cases where you need the absolute simplest way to persist data in the browser.
How to use the LocalStorage RxStorage with RxDBβ
Import the Storageβ
import { createRxDatabase } from 'rxdb/plugins/core';
import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage';
Create a Databaseβ
const db = await createRxDatabase({
name: 'exampledb',
storage: getRxStorageLocalstorage()
});
Add a Collectionβ
await db.addCollections({
tasks: {
schema: {
title: 'tasks schema',
version: 0,
primaryKey: 'id',
type: 'object',
properties: {
id: { type: 'string' },
title: { type: 'string' },
done: { type: 'boolean' }
},
required: ['id', 'title', 'done']
}
}
});
Insert a documentβ
await db.tasks.insert({ id: 'task-01', title: 'Get started with RxDB' });
Query documentsβ
const nonDoneTasks = await db.tasks.find({
selector: {
done: {
$eq: false
}
}
}).exec();
Mocking the LocalStorage API for testing in Node.jsβ
While the localStorage
API only exists in browsers, your can the LocalStorage based storage in Node.js by using the mock that comes with RxDB.
This is intended to be used in unit tests or other test suites:
import { createRxDatabase } from 'rxdb/plugins/core';
import {
getRxStorageLocalstorage,
getLocalStorageMock
} from 'rxdb/plugins/storage-localstorage';
const db = await createRxDatabase({
name: 'exampledb',
storage: getRxStorageLocalstorage({
localStorage: getLocalStorageMock()
})
});