JS Firebase API

Firebase Realtime Database API

Firebase is a powerful platform offering various services to enhance our web application. From authentication to real-time database storage, Firebase provides everything you need to create a dynamic and engaging user experience.

Firebase is a platform made by Google that helps developers build apps easily. One of its most powerful features is the Realtime Database. The Realtime Database lets you store and sync data in real-time across all clients, which means every time someone updates the data, everyone sees the change immediately.

Setting Up Firebase Realtime Database

You must set it up before you can start using Firebase Realtime Database. Don’t worry, it’s easy! Follow these steps:

Create a Firebase Project:

Go to the Firebase console. You’ll be prompted to select an existing Firebase project. Follow the database creation workflow.

Click on “Add Project” and follow the instructions.

JS-Firebase-project

After clicking on this give a name to your project and click continue

JS-fire-
JS-Fire-Ana-

Right now we don’t need to enable Google Analytics for the project, so disable it click on Create Project wait a little bit, and click Continue and your project is created.

After that click on Create database

JS-Set-up-database

Select a starting mode for your Firebase Security Rules:

 

 Test mode: Good for getting started with the mobile and web client libraries, but allows anyone to read and overwrite your data.

 Locked mode: Denies all reads and writes from mobile and web clients. Your authenticated application servers can still access your database.

After clicking enable this page will show:

JS-Realtime-database

Click on rules and change both(read,write) rules from false to true and click on publish

Adding Firebase to Your App:

  Whether you’re building a web or mobile app, you’ll need to add Firebase SDK to your project. Firebase has detailed steps for different types of apps (e.g., iOS, Android, or Web).

After this go on a project overview and click on the web , to add Firebase to your app follow these steps:

Step1:

JS-Firebase-step1

Step2:

JS-Firebase-web

After this, we will select the script tag because we’re going to write code in JavaScript

JS-Add-firebase

Copy your Firebase SDK code Paste it on the script.js file and click continue to console.

Your Firebase setup has been done

Basic Operations in Firebase Realtime Database

Once everything is set up, you can start using the database to store, read, update, and delete data. Let’s look at how you can do these operations using JavaScript.

1. Storing Data in Database

// Import the functions you need from the SDKs you need
import { initializeApp } from “https://www.gstatic.com/firebasejs/11.1.0/firebase-app.js”;
import { getDatabase ,set,get,ref } from “https://www.gstatic.com/firebasejs/11.1.0/firebase-database.js”;
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app’s Firebase configuration
const firebaseConfig = {
apiKey: “YOUR_API_KEY”, // Replace with your actual API key
authDomain: “YOUR_PROJECT_ID.firebaseapp.com”, // Replace with your project’s domain
databaseURL: “https://YOUR_PROJECT_ID.firebaseio.com”, // Replace with your database URL
projectId: “YOUR_PROJECT_ID”, // Replace with your Firebase project ID
storageBucket: “YOUR_PROJECT_ID.appspot.com”, // Replace with your storage bucket
messagingSenderId: “YOUR_MESSAGING_SENDER_ID”, // Replace with your messaging sender ID
appId: “YOUR_APP_ID”, // Replace with your app ID
measurementId: “YOUR_MEASUREMENT_ID”, // Optional: for Firebase Analytics
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
function writeUserData(userID,name,email){
set(ref(db,’users/’+ userID),{
name:name,
email:email
})
}
writeUserData(1,’saad’,’saad@gmail.com’)
writeUserData(2,’amir’,’amir@gmail.com’)

Code Explanation:

1. Importing Firebase Functions:

import { initializeApp } from “https://www.gstatic.com/firebasejs/11.1.0/firebase-app.js”;
import { getDatabase, set, get, ref } from “https://www.gstatic.com/firebasejs/11.1.0/firebase-database.js”;

Here, you’re importing the necessary functions from the Firebase SDK:

•  initializeApp: This function initializes Firebase in your app with the provided configuration.
  getDatabase: This function is used to get a reference to the Firebase Realtime Database service.
  set: This function is used to write data to a specific location in the Firebase Realtime Database.
  get: This function is used to retrieve data from a specific location in the Firebase Realtime Database.
•  ref: This function is used to create a reference to a specific path in the Firebase Realtime Database.

2. Firebase Configuration:

const firebaseConfig = {
apiKey: “YOUR_API_KEY”, // Replace with your actual API key
authDomain: “YOUR_PROJECT_ID.firebaseapp.com”, // Replace with your project’s domain
databaseURL: “https://YOUR_PROJECT_ID.firebaseio.com”, // Replace with your database URL
projectId: “YOUR_PROJECT_ID”, // Replace with your Firebase project ID
storageBucket: “YOUR_PROJECT_ID.appspot.com”, // Replace with your storage bucket
messagingSenderId: “YOUR_MESSAGING_SENDER_ID”, // Replace with your messaging sender ID
appId: “YOUR_APP_ID”, // Replace with your app ID
measurementId: “YOUR_MEASUREMENT_ID”, // Optional: for Firebase Analytics
};

This block contains the Firebase project configuration for your web app:

•  apiKey: The unique API key used to authenticate your app with Firebase.
  authDomain: The domain for Firebase Authentication (though it’s not used in the code you provided).
•  databaseURL: The URL pointing to your Firebase Realtime Database instance.
  projectId: The unique ID for your Firebase project.
•  storageBucket: The location for storing files in Firebase Storage (again, not used in this example).
  messagingSenderId: Used for Firebase Cloud Messaging, though not relevant in this example.
  appId: The unique identifier for your app within Firebase.
  measurementId: Used for Firebase Analytics (optional).

3. Initializing Firebase:

const app = initializeApp(firebaseConfig);

This line initializes Firebase with the configuration provided above. It’s necessary to connect your web app to your Firebase project. The initializeApp function takes the firebaseConfig and links it to your app.

4. Creating a Database Reference:

const db = getDatabase(app);

This line gets a reference to the Firebase Realtime Database instance associated with the Firebase project. By calling getDatabase, you’re setting up a connection to the Realtime Database, allowing you to perform operations like reading, writing, and updating data.

5. Function to Write Data to the Database:

function writeUserData(userID, name, email) {
set(ref(db, ‘users/’ + userID), {
name: name,
email: email
});
}

writeUserData is a custom function that writes user data to the Firebase Realtime Database.

Parameters: It takes three parameters—userID, name, and email.

ref(db, ‘users/’ + userID): This creates a reference to the path in the database where the user’s data will be stored. The path is users/userID, where userID is dynamically replaced by the actual user ID. So, for userID = 1, it will write to users/1.

set(…): The set function writes the data to the location specified by the reference. Here, it writes the name and email to that user’s location.

6. Calling the Function to Write Data:

writeUserData(1, ‘saad’, ‘saad@gmail.com’);
writeUserData(2, ‘amir’, ‘amir@gmail.com’);

These two calls to writeUserData write data for two users with user IDs 1 and 2:

  The first call writes the name “saad” and email “saad@gmail.com” to the users/1 path.
•  The second call writes the name “amir” and email “amir@gmail.com” to the users/2 path.

2. Reading Data

function readData(){
const useref = ref(db,’users’)
get(useref).then((snapshot)=>{
snapshot.forEach((childsnapShot)=>{
console.log(childsnapShot.val());

})
})
}
readData();

Code explanation:

1. Function Definition:

function readData() {

This is the definition of the readData function. It doesn’t take any parameters and its purpose is to read data from the Firebase Realtime Database.

2. Creating a Reference to the Database:

const useref = ref(db, ‘users’);

•  ref(db, ‘users’): This line creates a reference to the user’s path in the Firebase Realtime Database. The ref function is used to specify the location (or path) in the database that we want to work with. In this case, we are pointing to the user’s path, which contains all the user data stored in the database.
• db: This is the instance of the Firebase Realtime Database, which was initialized earlier in your code (const db = getDatabase(app)).

3. Getting Data with the get() Method:

get(useref).then((snapshot) => {

get(useref): The get function is used to retrieve data from the specified reference (useref, which points to the user’s path). It returns a promise that resolves to a snapshot of the data at that reference.

Snapshot: This is an object representing the data returned from Firebase. It contains all the information stored in the database at the user’s path.

4. Iterating Over the Child Nodes:

snapshot.forEach((childSnapshot) => {
console.log(childSnapshot.val());
});

snapshot.forEach(): The snapshot object represents the entire data at the users path, and it can contain multiple child nodes (each child represents one user).

forEach(): This method is used to loop over each child node in the snapshot.

childSnapshot: Represents each child (in this case, each user) at the users path.

childSnapshot.val(): This method retrieves the data of that child (user) in the form of an object. For example, if a user has a name and email, it would return an object like { name: ‘saad’, email: ‘saad@gmail.com’ }.

5. Logging the Data:

console.log(childSnapshot.val());

For each user (or child), it logs the data to the console. The data is logged as an object, containing the properties (e.g., name and email) stored for each user at that specific path.

6. Calling the readData Function:

readData();

This line calls the readData function to execute the code that fetches and logs the user data.

Output

JS-Read-data

3. Deleting Data

function deleteUserByName(name) {
const usersRef = ref(db, ‘users’);
get(usersRef).then((snapshot) => {
snapshot.forEach((childSnapshot) => {
const user = childSnapshot.val();
if (user.name === name) {
// User found, delete their data
remove(childSnapshot.ref)
.then(() => {
console.log(`User ${name} deleted successfully`);
})
.catch((error) => {
console.error(‘Error deleting user:’, error);
});
}
});
});
}

// Deleting a user by name (“saad”)
deleteUserByName(“saad”);

Code explanation:

1. Function Declaration:

function deleteUserByName(name) {

This function is named deleteUserByName and it accepts a parameter name, which is the name of the user you want to delete from the Firebase Realtime Database.

2. Get the Reference to Users:

const usersRef = ref(db, ‘users’);

This line creates a reference to the ‘users’ node in the Firebase Realtime Database. The db object is the initialized Firebase database reference, and users is the collection (node) in the database that stores user data.

3. Get Data from Firebase:

get(usersRef).then((snapshot) => {

get(usersRef) retrieves all data under the users node from Firebase. It returns a snapshot, which contains the entire data under ‘users’.
snapshot is an object containing all the data from Firebase at that path.

4. Iterate Through Users:

snapshot.forEach((childSnapshot) => {

This line iterates over each child of the users node. Each childSnapshot represents one user object from the database.

Each user is stored under a unique key (usually a user ID), and the iteration will allow you to check each user’s data.

5. Access the User Data:

const user = childSnapshot.val();

childSnapshot.val() retrieves the data for that specific user from the database. This will return an object containing the user’s data (e.g., name, email, etc.).

6. Check if the User's Name Matches:

if (user.name === name) {

This line checks if the name field of the current user matches the name passed into the function.

If the condition is true, it means the user with the given name has been found, and we can proceed to delete that user’s data.

7. Delete the User Data:

remove(childSnapshot.ref)
.then(() => {
console.log(`User ${name} deleted successfully`);
})
.catch((error) => {
console.error(‘Error deleting user:’, error);
});

remove(childSnapshot.ref) deletes the data for that user from Firebase. The childSnapshot.ref gives the reference to the user’s data in the database, allowing the remove() function to target and delete that specific node.

If the deletion is successful, the then() block is executed, and a success message is logged: User ${name} deleted successfully.

If an error occurs during the deletion, the catch() block is executed, and an error message is logged.

8.Function Call:

deleteUserByName(“saad”);

This line calls the deleteUserByName function with the argument “saad”, which means the function will search for a user with the name “saad” and delete their data from Firebase if found.

Output

Course Video

YouTube Reference :

Practice Scenarios

1. Adding Data to Firebase Using Promises

Objective: Understand how to write data to Firebase and handle the promise result.

Question:
Write a function that adds a new user to the users node in the Firebase database and logs a success or error message based on the result.

Here’s an example:

<body>
<script type=”module”>
// Import the functions you need from the SDKs you need
import { initializeApp } from “https://www.gstatic.com/firebasejs/11.1.0/firebase-app.js”;
import { getDatabase, set, get, ref } from “https://www.gstatic.com/firebasejs/11.1.0/firebase-database.js”;
// Your web app’s Firebase configuration
const firebaseConfig = {
apiKey: “YOUR_API_KEY”,
authDomain: “YOUR_AUTH_DOMAIN”,
databaseURL: “YOUR_DATABASE_URL”,
projectId: “YOUR_PROJECT_ID”,
storageBucket: “YOUR_STORAGE_BUCKET”,
messagingSenderId: “YOUR_MESSAGING_SENDER_ID”,
appId: “YOUR_APP_ID”
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
function writeUserData(userID, name, email) {
set(ref(db, ‘users/’ + userID), {
name: name,
email: email
})
}
writeUserData(1, “saad”, “saad@gmail.com”)
writeUserData(2, “amir”, “amir@gmail.com”)
function readData() {
const useref = ref(db, ‘users’)
get(useref).then((snapshot) => {
snapshot.forEach((childsnapShot) => {
console.log(childsnapShot.val());
})
})
}
readData();

</script>
</body>

Output
JS-Adding-data
2. Update a User's Email

Question: Modify the writeUserData() function to update the email of an existing user, Question: Modify the writeUserData() function to update the email of an existing user, without overwriting other fields (name should remain unchanged).

Hint: Use .update() instead of .set() to update only specific fields.

Here’s an example:

<body>
<script type=”module”>
// Import the functions you need from the SDKs you need
import { initializeApp } from “https://www.gstatic.com/firebasejs/11.1.0/firebase-app.js”;
import { getDatabase, set, get, ref } from “https://www.gstatic.com/firebasejs/11.1.0/firebase-database.js”;
// Your web app’s Firebase configuration
const firebaseConfig = {
apiKey: “YOUR_API_KEY”,
authDomain: “YOUR_AUTH_DOMAIN”,
databaseURL: “YOUR_DATABASE_URL”,
projectId: “YOUR_PROJECT_ID”,
storageBucket: “YOUR_STORAGE_BUCKET”,
messagingSenderId: “YOUR_MESSAGING_SENDER_ID”,
appId: “YOUR_APP_ID”
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
function writeUserData(userID, name, email) {
set(ref(db, ‘users/’ + userID), {
name: name,
email: email
})
}
writeUserData(1, “saad”, “saad@gmail.com”)
writeUserData(2, “amir”, “amir@gmail.com”)
function updateUserEmail(userID, newEmail) {
const userRef = ref(db, ‘users/’ + userID);
set(userRef, {
email: newEmail
}).then(() => {
console.log(“User email updated successfully!”);
}).catch((error) => {
console.log(“Error updating email:”, error);
});
}

updateUserEmail(1, “newemail@example.com”);

function readData() {
const useref = ref(db, ‘users’)
get(useref).then((snapshot) => {
snapshot.forEach((childsnapShot) => {
console.log(childsnapShot.val());

})
})
}
readData();

</script>
</body>

Output
JS-User-update
3. Delete a User by ID

Question: Write a function to delete a user by their userID.

Here’s an example:

<body>

    <script type=”module”>

 

        // Import the functions you need from the SDKs you need

        import { initializeApp } from “https://www.gstatic.com/firebasejs/11.1.0/firebase-app.js”;

        import { getDatabase, set, get, ref, remove } from “https://www.gstatic.com/firebasejs/11.1.0/firebase-database.js”;

       

        // Your web app’s Firebase configuration

        const firebaseConfig = {

    apiKey: “YOUR_API_KEY”,

    authDomain: “YOUR_AUTH_DOMAIN”,

    databaseURL: “YOUR_DATABASE_URL”,

    projectId: “YOUR_PROJECT_ID”,

    storageBucket: “YOUR_STORAGE_BUCKET”,

    messagingSenderId: “YOUR_MESSAGING_SENDER_ID”,

    appId: “YOUR_APP_ID”

};

        // Initialize Firebase

        const app = initializeApp(firebaseConfig);

        const db = getDatabase(app);

 

        // Function to delete a user by userID

        function deleteUser(userID) {

            const userRef = ref(db, ‘users/’ + userID);

            remove(userRef) // This will delete the user from the database

                .then(() => {

                    console.log(`User with ID ${userID} has been deleted successfully.`);

                })

                .catch((error) => {

                    console.error(“Error deleting user:”, error);

                });

        }

 

        // Call the deleteUser function for a specific userID (example userID = 1)

        deleteUser(1);  // You can change this to delete any other user (e.g., 2)

 

        // Optional: After deleting, you can also read the remaining data to check if deletion was successful

        function readData() {

            const useref = ref(db, ‘users’);

            get(useref).then((snapshot) => {

                snapshot.forEach((childSnapshot) => {

                    console.log(childSnapshot.val());

                });

            }).catch((error) => {

                console.error(“Error reading data:”, error);

            });

        }

 

        readData(); // To confirm deletion of user 1

 

    </script>

</body>

Output
4. Add Multiple Users in Parallel Using Promise.all

Question: Write a function to add multiple users in parallel (e.g., user1 and user2). Use Promise.all() to ensure both writes are complete before logging a success message.

Here’s an example:

<body>
<script type=”module”>

// Import the functions you need from the SDKs you need
import { initializeApp } from “https://www.gstatic.com/firebasejs/11.1.0/firebase-app.js”;
import { getDatabase, set, get, ref } from “https://www.gstatic.com/firebasejs/11.1.0/firebase-database.js”;
// Your web app’s Firebase configuration
const firebaseConfig = {
apiKey: “YOUR_API_KEY”,
authDomain: “YOUR_AUTH_DOMAIN”,
databaseURL: “YOUR_DATABASE_URL”,
projectId: “YOUR_PROJECT_ID”,
storageBucket: “YOUR_STORAGE_BUCKET”,
messagingSenderId: “YOUR_MESSAGING_SENDER_ID”,
appId: “YOUR_APP_ID”
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
function writeUserData(userID, name, email) {
set(ref(db, ‘users/’ + userID), {
name: name,
email: email
})
}
writeUserData(1, “saad”, “saad@gmail.com”)
writeUserData(2, “amir”, “amir@gmail.com”)
function addUsersInParallel(user1, user2) {
const addUser1 = set(ref(db, ‘users/’ + user1.id), user1);
const addUser2 = set(ref(db, ‘users/’ + user2.id), user2);

Promise.all([addUser1, addUser2])
.then(() => {
console.log(“Both users added successfully”);
})
.catch((error) => {
console.log(“Error adding users:”, error);
});
}

addUsersInParallel(
{ id: 3, name: ‘Zara’, email: ‘zara@example.com’ },
{ id: 4, name: ‘Liam’, email: ‘liam@example.com’ }
);

 

function readData() {
const useref = ref(db, ‘users’)
get(useref).then((snapshot) => {
snapshot.forEach((childsnapShot) => {
console.log(childsnapShot.val());

})
})
}
readData();

</script>
</body>

Output
JS-Multiple