@react-native-firebase/appinstalled and native config completed per Getting Started (Androidgoogle-services.json, iOSGoogleService-Info.plist, Expo config plugin, or React Native CLI setup). From v26, New Architecture is required for packages with a native bridge.- Install Database:
npm install --save @react-native-firebase/databaseoryarn add @react-native-firebase/database, then rebuild native apps (cd ios && pod installon iOS). - Enable Realtime Database in the Firebase Console for your project and deploy security rules appropriate for your app.
Example Expo Router screen: https://github.com/invertase/react-native-firebase/blob/main/test-expo/app/database.tsx
This module requires that the @react-native-firebase/app module is already setup and installed. To install the "app" module, view the
Getting Started documentation.
# Install & setup the app module
yarn add @react-native-firebase/app
# Install the database module
yarn add @react-native-firebase/database
# If you're developing your app using iOS, run this command
cd ios/ && pod install && cd ..{/* prettier-ignore */}
| Platforms | Android, iOS (native Firebase SDK) |
| New Architecture | Required from v26. See Migrating to v26. |
Platform notes: React Native Firebase also exports SDK_VERSION, setPersistenceEnabled, setLoggingEnabled, setPersistenceCacheSizeBytes, getServerTime, and keepSynced. Each is explained in the section that uses it (or on Offline Support).
The Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client. React Native Firebase provides native integration with the Android & iOS Firebase SDKs, supporting both realtime data sync and offline capabilities.
To learn more, view the Firebase Realtime Database documentation.
Use connectDatabaseEmulator before any Realtime Database reads or writes when talking to the Local Emulator Suite (the Realtime Database emulator listens on port 9000 by default). On Android emulators, use 10.0.2.2 instead of localhost / 127.0.0.1 so the guest can reach the host machine.
import { Platform } from 'react-native';
import { connectDatabaseEmulator, getDatabase } from '@react-native-firebase/database';
const host = Platform.OS === 'android' ? '10.0.2.2' : '127.0.0.1';
connectDatabaseEmulator(getDatabase(), host, 9000);A core concept to understanding Realtime Database are references - a reference to a specific node within your database. A node can be a specific property or sub-nodes.
To create a Reference, use the ref function:
import { getDatabase, ref } from '@react-native-firebase/database';
const db = getDatabase();
const reference = ref(db, '/users/123');
console.log('Reference path:', reference.toString());NOTE: To get a reference to a database other than a 'us-central1' default database, you must pass the database URL. You can find your Realtime Database URL in the Realtime Database section of the Firebase console.
import { getDatabase, ref } from '@react-native-firebase/database';
const db = getDatabase(undefined, 'https://<databaseName>.<region>.firebasedatabase.app/');
const reference = ref(db, '/users/123');
console.log('Secondary-region reference path:', reference.toString());Create a child reference with child, or rebuild a reference from a full database URL with refFromURL (the URL must be on the same domain as the current database instance):
import { getApp } from '@react-native-firebase/app';
import { child, getDatabase, ref, refFromURL } from '@react-native-firebase/database';
const db = getDatabase();
const usersRef = ref(db, '/users');
const userRef = child(usersRef, '123');
console.log('Child path:', userRef.toString());
const databaseURL = getApp().options.databaseURL;
const fromUrl = refFromURL(db, `${databaseURL}/users/123`);
console.log('refFromURL path:', fromUrl.toString());The Realtime Data provides the ability to read the value of a reference as a one-time read, or realtime changes to the node.
When a value is read from the database, the API returns a DataSnapshot.
The snapshot includes information such as whether the reference node exists, it's value or any children the node has and more.
To read the value once, use get:
import { getDatabase, ref, get } from '@react-native-firebase/database';
const db = getDatabase();
get(ref(db, '/users/123')).then(snapshot => {
console.log('User data: ', snapshot.val());
});Prefer get() when you need a server round-trip. When you want a one-shot observer (for example to take a value from the local cache without keeping a live subscription), pass { onlyOnce: true } as the last argument to onValue. The listener runs once, then detaches:
import { getDatabase, ref, onValue } from '@react-native-firebase/database';
const db = getDatabase();
onValue(
ref(db, '/users/123'),
snapshot => {
console.log('User data:', snapshot.val());
},
{ onlyOnce: true },
);To setup an active listener to react to any changes to the node and it's children, use onValue:
import { getDatabase, ref, onValue } from '@react-native-firebase/database';
const db = getDatabase();
const unsubscribe = onValue(ref(db, '/users/123'), snapshot => {
console.log('User data: ', snapshot.val());
});
// Call unsubscribe() when the listener is no longer needed.
console.log('Listening; unsubscribe is a function:', typeof unsubscribe);The event handler will be called straight away with the snapshot data, and further called when any changes to the node occur.
You can unsubscribe by calling the function returned from onValue. This can be used within any useEffect hooks to automatically unsubscribe
when the hook needs to unsubscribe itself:
import { useEffect } from 'react';
import { getDatabase, ref, onValue } from '@react-native-firebase/database';
function User({ userId }) {
useEffect(() => {
const db = getDatabase();
const unsubscribe = onValue(ref(db, `/users/${userId}`), snapshot => {
console.log('User data: ', snapshot.val());
});
// Stop listening for updates when no longer required
return () => unsubscribe();
}, [userId]);
return null;
}The above example demonstrates how to subscribe to events whenever a value within the node changes. In some cases, you
may need to only subscribe to events whenever a child node is added/changed/moved/removed. This can be achieved using
a different listener such as onChildAdded.
If you are listening to a node with many children, only listening to data you care about helps reduce network bandwidth and speeds up your application.
import { useEffect } from 'react';
import { getDatabase, ref, onChildAdded } from '@react-native-firebase/database';
function User({ userId }) {
useEffect(() => {
const db = getDatabase();
const unsubscribe = onChildAdded(ref(db, '/users'), snapshot => {
console.log('A new node has been added', snapshot.val());
});
// Stop listening for updates when no longer required
return () => unsubscribe();
}, [userId]);
return null;
}The same pattern applies to onChildChanged, onChildMoved, and onChildRemoved when you only care about those list mutations:
import {
getDatabase,
ref,
onChildChanged,
onChildMoved,
onChildRemoved,
} from '@react-native-firebase/database';
const db = getDatabase();
const usersRef = ref(db, '/users');
const stopChanged = onChildChanged(usersRef, snapshot => {
console.log('Child changed:', snapshot.key, snapshot.val());
});
const stopMoved = onChildMoved(usersRef, snapshot => {
console.log('Child moved:', snapshot.key);
});
const stopRemoved = onChildRemoved(usersRef, snapshot => {
console.log('Child removed:', snapshot.key, snapshot.val());
});
console.log('Child listeners attached:', typeof stopChanged, typeof stopMoved, typeof stopRemoved);Call the function returned from onValue / onChild* to unsubscribe. The modular off() helper is not implemented on React Native Firebase and always throws (off() is not implemented - use unsubscriber callback returned when subscribing).
import { getDatabase, ref, onValue, off } from '@react-native-firebase/database';
const db = getDatabase();
const userRef = ref(db, '/users/123');
const unsubscribe = onValue(userRef, snapshot => {
console.log('User data:', snapshot.val());
});
// Prefer the returned unsubscribe function:
unsubscribe();
try {
// WARNING: off() always throws on React Native Firebase.
off(userRef);
} catch (error) {
console.log('Expected off() error:', error instanceof Error ? error.message : error);
}Realtime Database provides support for basic querying of your data. When a reference node contains children, you can both order & limit the returned results.
If your application requires more advanced query capabilities, it is recommended you use Cloud Firestore.
By default, results are ordered based on the node keys. If however you are using custom keys you can use
the orderByX query constraints with query to order your data.
For example, if all of the nodes children are scalar values (string, number or boolean) you can use orderByValue,
and Firebase will automatically order the results. The example below would return the def node before the abc node:
/*
* {
* 'scores': {
* 'abc': 30,
* 'def': 50,
* }
* }
*/
import { getDatabase, ref, query, orderByValue, get } from '@react-native-firebase/database';
async function readScoresOrderedByValue() {
const db = getDatabase();
const snapshot = await get(query(ref(db, 'scores'), orderByValue()));
snapshot.forEach(child => {
console.log(child.key, child.val());
return undefined;
});
}Please note that the ordering will not be respected if you do not use the forEach method provided on the DataSnapshot.
orderByChild, orderByKey, and orderByValue each apply fixed type-precedence rules. Walk ordered children with snapshot.forEach so iteration follows that order (plain Object key order does not).
For orderByChild (and for orderByValue, using each child's own value instead of a named child), children sort in this sequence:
- Missing /
nullfor the ordered field first. - Then
false, thentrue(ties broken by key string order). - Then numbers ascending (ties by key).
- Then strings in ascending string order (ties by key).
- Then objects, sorted by key string order ascending.
orderByKey is different: keys that parse as 32-bit integers come first (numeric ascending), then remaining string keys in ascending string order. So under orderByKey, sibling keys "10", "2", and "a" iterate as 2, then 10, then a:
import { getDatabase, ref, query, orderByKey, get } from '@react-native-firebase/database';
async function readChildrenOrderedByKey() {
const db = getDatabase();
const snapshot = await get(query(ref(db, 'items'), orderByKey()));
snapshot.forEach(child => {
console.log(child.key);
return undefined;
});
}You can limit the number of results returned from a query by using limitToFirst or limitToLast query constraints. For example, to limit to the
first 10 results:
import { getDatabase, ref, query, limitToFirst, get } from '@react-native-firebase/database';
async function readFirstTenUsers() {
const db = getDatabase();
const snapshot = await get(query(ref(db, 'users'), limitToFirst(10)));
console.log('First ten users:', snapshot.val());
}Firebase also provides the ability to return the last set of results in a query via limitToLast.
Instead of limiting to a specific number of documents, you can also start from, or end at a specific reference node value:
import {
getDatabase,
ref,
query,
orderByChild,
startAt,
get,
} from '@react-native-firebase/database';
async function readUsersAgedTwentyOneOrOlder() {
const db = getDatabase();
const snapshot = await get(query(ref(db, 'users'), orderByChild('age'), startAt(21)));
console.log('Users aged 21+:', snapshot.val());
}You can also order by key or priority, and filter with equalTo, startAfter, endAt, or endBefore:
import {
getDatabase,
ref,
query,
orderByChild,
orderByKey,
orderByPriority,
equalTo,
startAfter,
endAt,
endBefore,
get,
} from '@react-native-firebase/database';
async function readFilteredUsers() {
const db = getDatabase();
const usersRef = ref(db, 'users');
const byKey = await get(query(usersRef, orderByKey(), startAfter('user-100'), endAt('user-200')));
console.log('Users by key range:', byKey.val());
const before = await get(query(usersRef, orderByKey(), endBefore('user-050')));
console.log('Users before key:', before.val());
const byPriority = await get(query(usersRef, orderByPriority()));
console.log('Users by priority:', byPriority.val());
const admins = await get(query(usersRef, orderByChild('role'), equalTo('admin')));
console.log('Admin users:', admins.val());
}The Firebase documentation provides great examples on best practices on how to structure your data. We highly recommend reading the guide before building out your database.
The set function overwrites all of the existing data at that reference node.
The value can be anything; a string, number, object etc:
import { getDatabase, ref, set } from '@react-native-firebase/database';
const db = getDatabase();
set(ref(db, '/users/123'), {
name: 'Ada Lovelace',
age: 31,
}).then(() => console.log('Data set.'));If you set the value to null, Firebase will automatically class the node as removed, and delete it from the database.
Use setPriority or setWithPriority when ordering children with orderByPriority:
import { getDatabase, ref, setPriority, setWithPriority } from '@react-native-firebase/database';
async function writeWithPriority() {
const db = getDatabase();
const userRef = ref(db, '/users/123');
await setWithPriority(userRef, { name: 'Ada Lovelace', age: 31 }, 1);
await setPriority(userRef, 2);
console.log('Priority updated.');
}Rather than overwriting all existing data, the update function provides the ability to update any existing data on the reference node.
Firebase will automatically merge the data depending on what currently exists.
import { getDatabase, ref, update } from '@react-native-firebase/database';
const db = getDatabase();
update(ref(db, '/users/123'), {
age: 32,
}).then(() => console.log('Data updated.'));When the same record is stored under more than one path (for example a global posts list and a per-user posts list), write both locations in one update call. Keys in the updates map are paths relative to the reference you pass to update. Generate a shared key with push(...).key, then write the same payload to each path. The write is atomic: every path succeeds or none do.
import { getDatabase, ref, child, push, update } from '@react-native-firebase/database';
function writeNewPost(uid, username, picture, title, body) {
const db = getDatabase();
const postData = {
author: username,
uid: uid,
body: body,
title: title,
starCount: 0,
authorPic: picture,
};
const newPostKey = push(child(ref(db), 'posts')).key;
const updates = {};
updates[`/posts/${newPostKey}`] = postData;
updates[`/user-posts/${uid}/${newPostKey}`] = postData;
return update(ref(db), updates);
}
writeNewPost('user-1', 'Ada', 'https://example.com/ada.png', 'Hello', 'First post').then(() =>
console.log('Post written to posts and user-posts.'),
);The earlier examples address nodes by known reference keys (e.g. /users/123). In some cases,
you may not have a suitable id or may want Firebase to automatically create a node with a generated key. The push function
returns a ThenableReference, allowing you to observe a node before it is
sent to remote Firebase database.
push will automatically generate a new key if one is not provided:
import { getDatabase, ref, push, set } from '@react-native-firebase/database';
const db = getDatabase();
const newReference = push(ref(db, '/users'));
console.log('Auto generated key: ', newReference.key);
set(newReference, {
age: 32,
}).then(() => console.log('Data updated.'));The keys generated are ordered to the current time, so the list of items returned from Firebase will be chronologically sorted by default.
serverTimestamp() writes a server-generated timestamp sentinel. increment(delta) writes an atomic server-side increment sentinel (useful instead of a transaction when you only need to bump a counter):
import {
getDatabase,
ref,
update,
serverTimestamp,
increment,
} from '@react-native-firebase/database';
async function stampAndIncrementLikes(postId) {
const db = getDatabase();
await update(ref(db, `/posts/${postId}`), {
lastUpdated: serverTimestamp(),
likeCount: increment(1),
});
console.log('Post stamped and likeCount incremented.');
}To remove data, use the remove function:
import { getDatabase, ref, remove } from '@react-native-firebase/database';
async function removeUser() {
await remove(ref(getDatabase(), '/users/123'));
console.log('User removed.');
}Optionally, you can also set the value of a reference node to null to remove it from the database:
import { getDatabase, ref, set } from '@react-native-firebase/database';
async function removeUserBySettingNull() {
await set(ref(getDatabase(), '/users/123'), null);
console.log('User removed by setting null.');
}Transactions are a way to always ensure a write occurs with the latest information available on the server. Transactions never partially apply writes & all writes execute at the end of a successful transaction.
Imagine a scenario whereby an app has the ability to "Like" user posts. Whenever a user presses the "Like" button,
the /likes/:postId value (number of likes) on the database increments. Without transactions, we'd first need to
read the existing value and then increment that value in two separate operations.
On a high traffic application, the value on the server could already have changed by the time the operation sets a new value, causing the actual number to not be consistent.
Transactions remove this issue by atomically updating the value on the server. If the value changes whilst the transaction is executing, it will retry. This always ensures the value on the server is used rather than the client value.
To execute a new transaction, call runTransaction:
import { getDatabase, ref, runTransaction } from '@react-native-firebase/database';
function onPostLike(postId) {
const db = getDatabase();
const reference = ref(db, `/likes/${postId}`);
return runTransaction(reference, currentLikes => {
if (currentLikes === null) return 1;
return currentLikes + 1;
});
}
// When post "567" is liked
onPostLike('567').then(transaction => {
console.log('New post like count: ', transaction.snapshot.val());
});Once the transaction is successful, a promise is resolved with a value containing whether the operation committed on the remote
database and the new DataSnapshot containing the new value.
setLoggingEnabled toggles native Realtime Database debug logging. On iOS the setting applies to all database instances. On Android the log level is set on each database instance as that instance is configured. Use it instead of the web-style enableLogging helper.
import { getDatabase, setLoggingEnabled } from '@react-native-firebase/database';
async function enableNativeDatabaseLogging() {
await setLoggingEnabled(getDatabase(), true);
console.log('Native database logging enabled.');
}Three functions exported by @react-native-firebase/database for web API parity are not implemented. Each throws a plain Error every time it is called, so do not call them in application code:
| Function | Error message | Alternative |
|---|---|---|
enableLogging() | enableLogging() is not implemented | setLoggingEnabled(db, enabled) |
forceLongPolling() | forceLongPolling() is not implemented | None on React Native Firebase (native transport). |
forceWebSockets() | forceWebSockets() is not implemented | None on React Native Firebase (native transport). |
// WARNING: forceLongPolling(), forceWebSockets() and enableLogging() always throw on React Native Firebase.
import { forceLongPolling, forceWebSockets, enableLogging } from '@react-native-firebase/database';
function showThrowingFunctions() {
const attempts = [() => forceLongPolling(), () => forceWebSockets(), () => enableLogging(true)];
for (const attempt of attempts) {
try {
attempt();
} catch (error) {
console.log('Expected error:', error instanceof Error ? error.message : error);
}
}
}
showThrowingFunctions();off() also always throws. See Detach listeners.
It is important that you understand how to write rules in your Firebase console to ensure that your data is secure. Please follow the Firebase Realtime Database documentation on security
If the default installed Firebase instance needs to address a different database within the same project, pass the database URL to getDatabase.
For example:
import { getDatabase, ref } from '@react-native-firebase/database';
const db = getDatabase(undefined, 'https://path-to-database.firebaseio.com');
const rootRef = ref(db);
console.log('Secondary database root:', rootRef.toString());If you want to address a database from a different Firebase project, you will need to create a secondary app first (Read more on creating a secondary app here: https://rnfirebase.io/app/usage). For example:
import { initializeApp } from '@react-native-firebase/app';
import { getDatabase, ref } from '@react-native-firebase/database';
// Secondary Firebase project credentials (replace placeholders).
const credentials = {
clientId: '1234567890-abc.apps.googleusercontent.com',
appId: '1:1234567890:ios:abcdef123456',
apiKey: 'AIzaSyExampleApiKeyForSecondaryApp',
databaseURL: 'https://my-secondary-project.firebaseio.com',
storageBucket: 'my-secondary-project.appspot.com',
messagingSenderId: '1234567890',
projectId: 'my-secondary-project',
};
const config = {
name: 'SECONDARY_APP',
};
async function connectSecondaryDatabase() {
const secondaryApp = await initializeApp(credentials, config);
const secondaryDb = getDatabase(secondaryApp);
const rootRef = ref(secondaryDb);
console.log('Secondary app database root:', rootRef.toString());
return secondaryDb;
}Disk persistence is off by default. Call setPersistenceEnabled once, before other database references are used in the app process, to let the native SDK cache data for offline use:
import { getDatabase, setPersistenceEnabled } from '@react-native-firebase/database';
async function enablePersistence() {
await setPersistenceEnabled(getDatabase(), true);
console.log('Database persistence enabled.');
}
enablePersistence();For more on persistence, view the Offline Support documentation.
SDK_VERSION is the React Native Firebase package version string exported from @react-native-firebase/database. The firebase-js-sdk does not export SDK_VERSION from @firebase/database.
import { SDK_VERSION } from '@react-native-firebase/database';
console.log('Database package version:', SDK_VERSION);
Core / App