Integrating with Other Firebase Services
- Integrating with Other Firebase Services involves using the various features and capabilities of Firebase to enhance the functionality and performance of our application.
- This integration typically involves using Firebase services such as Firebase Analytics, Firebase Cloud Messaging (FCM), Firebase Remote Config and Firebase Realtime Database among others to create interactive user experience.
- Letās understand with the below examples of Integration with various Firebase Services are defined below.
1. Firestore and Authentication
- Among multiple services Firebase offers, one of the most valuable is Firebase Authentication which provides all user management possibilities such as email/password, phone number sign-in, and third-party providers, like Google, Facebook, etc.
- Once users are signed in through Firebase Authentication, we can ensure that data in Cloud Firestore, a NoSQL document database is securely accessible and managed based on the context of the user.
Integration Steps:
1. Set Up Authentication: Enable the desired authentication methods in the Firebase console.
2. Initialize Authentication in your app
Letās Implement a mechanism in a Firebase application to track the authentication state of users in real-time, distinguishing between signed-in and signed-out states, and retrieve the user ID (UID) when the user is signed in.
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, user => {
if (user) {
// User is signed in
const uid = user.uid;
} else {
// User is signed out
}
});
Explanation: This code initializes Firebase Authentication and sets up a listener to track changes in the authentication state. When a user signs in or out, the corresponding action is executed, such as retrieving the userās unique identifier (UID) when signed in.
3. Secure Firestore:
Letās Create a security rule in Firestore to restrict access to the āusersā collection, allowing read and write operations only if the request is authenticated and the user ID matches the documentās user ID.
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}
Explanation: This Firestore security rule ensures that only authenticated users can read and write data in the āusersā collection. It verifies that the user making the request is authenticated and matches the user ID associated with the document being accessed.
4. Storing User Data:
Letās Implement a function in a Firebase application to add a new user document to the Firestore database with the provided user ID, name, and email, ensuring the data is stored securely and accurately.
import { getFirestore, doc, setDoc } from "firebase/firestore";
const db = getFirestore();
async function addUser(userId, name, email) {
await setDoc(doc(db, "users", userId), {
name: name,
email: email
});
}
Explanation: This code snippet initializes Firestore and defines an asynchronous function `addUser` to add user data to the Firestore database. It sets a document with the provided `userId`, `name`, and `email` in the āusersā collection.
2. Firestore and Cloud Functions
Cloud Functions for Firebase lets you run backend code in response to events triggered by Firebase features and HTTPS requests. This is particularly useful for automating tasks and implementing complex business logic.
Integration Steps:
1. Set Up Cloud Functions:
Letās Develop a Firebase Cloud Function that triggers when a new user is created, and automatically creates a corresponding user record in the Firestore database, storing the userās email and creation timestamp for further user management and analysis.
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
exports.createUserRecord = functions.auth.user().onCreate((user) => {
const userRef = db.collection('users').doc(user.uid);
return userRef.set({
email: user.email,
createdAt: admin.firestore.FieldValue.serverTimestamp()
});
});
Explanation: This code initializes Firebase Cloud Functions and Firestore. It creates a Cloud Function trigger that executes when a new user is created. Upon user creation, it retrieves the userās information (email and UID) and stores it in the āusersā collection of the Firestore database, along with the timestamp of creation.
2. Trigger Functions on Firestore Events:
Letās Design a Firebase Cloud Function that triggers when there are changes to the ratings of a product in the Firestore database, and implements logic to aggregate the ratings for that product, enabling real-time updates and analysis of product ratings.
exports.aggregateRatings = functions.firestore
.document('products/{productId}/ratings/{ratingId}')
.onWrite((change, context) => {
const productId = context.params.productId;
// Aggregate logic here
});
Explanation: This code defines a Cloud Function trigger that executes when there are changes to documents within the specified Firestore path (`products/{productId}/ratings/{ratingId}`). Upon such changes, it retrieves the `productId` from the context and performs aggregation logic, which could involve calculating average ratings or other statistical operations.
3. Firebase Storage and Firestore
Firebase Storage is used to store user-generated content such as photos and videos. Integrating it with Firestore can help keep metadata about the files, facilitating easy retrieval and management.
Integration Steps:
1. Set Up Storage:
Letās Implement functionality in a Firebase application to interact with Firebase Storage, allowing users to upload files and retrieve their download URLs, enhancing the applicationās ability to handle and manage user-generated content.
import { getStorage, ref, uploadBytes, getDownloadURL } from "firebase/storage";
const storage = getStorage();
const storageRef = ref(storage, 'some-child');
2. Upload and Store Metadata
Letās Create an asynchronous function in a Firebase application to upload a file to Firebase Storage, retrieve its download URL, and store metadata about the file in the Firestore database, enabling efficient file management and retrieval.
async function uploadFile(file) {
const snapshot = await uploadBytes(storageRef, file);
const url = await getDownloadURL(snapshot.ref);
await setDoc(doc(db, "files", snapshot.metadata.name), {
url: url,
name: file.name,
size: file.size
});
}
Integrating with Other Firebase Services
Firebase is an app development platform developed by Google that provides services to the application development process and enhances the users experience and the performance of the applications. So the Firebase integration of many services can provide a powerful addition to our applicationās functionality.
In this article, We will learn about How to Integrate with other Firebase services like Authentication and Firestore, Firestore and Cloud Functions and Firebase Storage and Firestore in detail