Realm Database for JavaScript
Realm JS is an offline-first, mobile-optimized database designed for JavaScript environments including React Native, Node.js, and Electron. It provides direct access to data as native JavaScript objects, eliminating the need for ORMs and offering performance often surpassing raw SQLite operations. The current stable major version is v20.x, with v20.2.0 being a recent release. Realm maintains a frequent release cadence, often with minor updates and bug fixes. A key differentiator was its integration with MongoDB Atlas Device Sync, but this feature was officially deprecated and removed starting with v20.0.0. Developers now using `realm` (v20+) should treat it as a robust local-only database, with a separate `community` package available for the sync-less version.
Common errors
-
Error opening or interacting with Realm: MultipleSyncAgents exception
cause Attempting to open a synchronized realm multiple times concurrently, often due to closing and reopening while a token refresh is in progress. (Applies to pre-v20 sync enabled versions)fixUpgrade to Realm JS v12.14.1 or newer. For v20+, sync features are removed, making this error specific to older versions. Ensure careful lifecycle management of Realm instances. -
Assertion failed: (key_type.has_primary_key()) && (new_key_type.has_primary_key())
cause Attempting to migrate a primary key field to a new type within a schema update without defining a migration function to handle the data transformation.fixUpgrade to Realm JS v12.14.1 or newer. When performing schema migrations that alter primary key types, ensure a comprehensive migration function is provided to correctly transform or re-index the data. -
Failed to install the app. Make sure you have the Android SDK installed and configured correctly. (or similar build error on React Native Android)
cause Build errors on React Native Android, particularly for React Native 0.76 due to changes in dynamic library merging or general native module linking issues.fixUpgrade to Realm JS v12.13.2 or later, which includes fixes for build errors on React Native Android when used with React Native 0.76 and newer. Also, try cleaning your Android build cache (`cd android && ./gradlew clean && cd ..`) and re-installing node modules. -
Invariant Violation: 'RCTBridgeModule' required for native module 'Realm' is null.
cause Common issue in React Native when the native module for Realm isn't correctly linked or initialized, often after an upgrade, cache corruption, or incorrect auto-linking.fixFor React Native, try `npx react-native start --reset-cache`, then `cd ios && pod install && cd ..`. Ensure your `Podfile` for iOS has `use_frameworks!` if needed. Verify compatibility with your `react-native` version and ensure auto-linking is functioning correctly (e.g., check `react-native config`).
Warnings
- breaking Atlas Device Sync functionality has been completely removed from Realm JS starting with v20.0.0. Applications relying on Device Sync will break and need to migrate to an alternative synchronization solution or use a pre-v20 version, understanding its limitations.
- breaking Realm JS v20.2.0 and v12.15.0 (and subsequent versions in these lines) do not support the deprecated legacy architecture of React Native. This impacts older React Native projects.
- gotcha Setting `List` values from themselves (e.g., `myObject.myList = myObject.myList`) could lead to unexpected emptying of the list due to an internal iteration bug.
- gotcha Closing and re-opening a synced realm before a token refresh completes could result in a crash with a 'MultipleSyncAgents' exception.
- gotcha The `excludeFromIcloudBackup` option was added to the `Realm` constructor to control whether realm files are included in iCloud backups on iOS. The default is `false` (included).
- gotcha Migrating a primary key to a new type without providing a migration function would cause an assertion to fail during schema migration.
Install
-
npm install realm -
yarn add realm -
pnpm add realm
Imports
- Realm
const Realm = require('realm');import Realm from 'realm';
- Configuration
import type { Configuration } from 'realm'; - ObjectSchema
import type { ObjectSchema } from 'realm';
Quickstart
import Realm from 'realm';
// Define your schema (object models)
class Car extends Realm.Object {
static schema = {
name: 'Car',
properties: {
make: 'string',
model: 'string',
miles: { type: 'int', default: 0 },
},
};
}
class Person extends Realm.Object {
static schema = {
name: 'Person',
properties: {
name: 'string',
cars: 'Car[]', // Define a relationship
},
};
}
// Open a realm with the defined schemas
async function runRealmExample() {
try {
const realm = await Realm.open({
path: 'myrealm.realm',
schema: [Car, Person],
schemaVersion: 1,
// Exclude from iCloud backup, useful for app-specific data that can be re-downloaded
excludeFromIcloudBackup: process.env.NODE_ENV === 'production' ? true : false,
});
// Write to the realm within a transaction
realm.write(() => {
const myCar = realm.create('Car', { make: 'Honda', model: 'Civic', miles: 1000 });
realm.create('Person', { name: 'Alice', cars: [myCar] });
realm.create('Car', { make: 'Toyota', model: 'Camry', miles: 5000 });
});
// Query objects
const cars = realm.objects('Car');
console.log(`Total cars in the realm: ${cars.length}`);
const hondas = cars.filtered('make == "Honda"');
console.log(`Number of Hondas: ${hondas.length}`);
// Update an object
realm.write(() => {
const civic = hondas[0];
if (civic) {
civic.miles += 500;
}
});
console.log(`Honda Civic miles after update: ${hondas[0]?.miles}`);
// Remember to close the realm when done to release resources
realm.close();
} catch (error) {
console.error("Error opening or interacting with Realm:", error);
}
}
runRealmExample();