Firebase for Web Development


(Useful : 1] Click)

Firebase is a Backend-as-a-Service (Baas). It provides developers with a variety of tools and services to help them develop quality apps, grow their user base, and earn profit. It is built on 

Google’s infrastructure. Below are some of the main features provided by the Firebase service :

  • Authentication
  • Realtime database
  • Firestore database
  • Cloud Storage
  • Security Rules
---------------------------------------------------------------------------------------------------------------

(Useful : 1] Click)


Firebase Authentication

Most of the time in order to add authentication to our applications we would require to setup an authentication server or database, in order to eliminate this hassle firebase provides the Authentication service.

Firebase Authentication aims to make building secure authentication systems easy, while improving the sign-in and onboarding experience for end users. It provides an end-to-end identity solution, supporting email and password accounts, phone auth, and Google, Twitter, Facebook, and GitHub login, and more. Below are some common functions used for Authentication in Firebase :
  • createUserWithEmailAndPassword() - It is used to register a new user.
  • signInWithEmailAndPassword() - It is used to authenticate the user.
  • onAuthStateChanged() - It triggers whenever user signIn or signOut.
NOTE : A useful feature of firebase authentication is that after a user is signedIn, it's state is persisted. Read more about it here.

Example] In the below example we demonstrate how to perform operations like SignUp, SignIn and Logout using Email & Password Authentication in Firebase.


// firebase-config.js

/* NOTE : You'll get this code snippet when you'll register
 your app inside the firebase project console. */

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

const firebaseConfig = {
  apiKey: "AIzaSyBaed0iaou97bmXAXbJ5RfHb_oKjynB0pQ",
  authDomain: "myreactapp-400c5.firebaseapp.com",
  projectId: "myreactapp-400c5",
  storageBucket: "myreactapp-400c5.appspot.com",
  messagingSenderId: "1087850171665",
  appId: "1:1087850171665:web:2b72554206c0ffec7190b0"
};

export const firebaseApp = initializeApp(firebaseConfig);
export const auth = getAuth(firebaseApp);



// App.js

import "./App.css";
import { useState } from "react";
import { auth } from "./firebase-config";
import { createUserWithEmailAndPassword,signInWithEmailAndPassword,
  onAuthStateChanged,signOut} from "firebase/auth";

//------------------------------------------------------------------------

const SignUp = () => {
  let email = null;
  let password = null;
  // NOTE : "auth.currentuser" also stores the currently logged in user.
  // currently signedIn user
  let [CurrentUser, setCurrentUser] = useState(null);

  //------------------------------------------------

  async function registerUser() {
    if (email == null || password == null) {
      window.alert("Email or Password Not Entered !");
      return;
    }
    try {
      // create new user and signIn
      const user = await createUserWithEmailAndPassword(auth, email, password);
      setCurrentUser(user.email);
    } catch (error) {
      const errorMessage = error.message;
      console.log("Signup Error : ", errorMessage);
    }
  }

  //------------------------------------------------

  function logOutUser() {
    signOut(auth)
      .then(() => {
        setCurrentUser(null);
        console.log("User logout sucess !");
      })
      .catch((error) => {
        const errorMessage = error.message;
        console.log("LogOut Error : ", errorMessage);
      });
  }

  //------------------------------------------------

  async function signInUser() {
    if (email == null || password == null) {
      window.alert("Email or Password Not Entered !");
      return;
    }
    try {
      // create new user and signIn
      const user = await signInWithEmailAndPassword(auth, email, password);
      setCurrentUser(user.email);
    } catch (error) {
      const errorMessage = error.message;
      console.log("SignIn Error : ", errorMessage);
    }
  }

  //------------------------------------------------

  // Triggers whenever auth state changes i.e user signIn/Out
  onAuthStateChanged(auth, (currentUser) => {
    console.log("onAuthStateChanged called !");
    if (currentUser != null) {
      setCurrentUser(currentUser.email);
    } else {
      setCurrentUser(null);
      console.log("User is loggedOut !");
    }
  });

  //------------------------------------------------

  return (
    <>
      <h1> Register User </h1>
      <input
        type="text"
        placeholder="Enter Email"
        onInput={(e) => (email = e.target.value)}/> &nbsp;
      <input
        type="text"
        placeholder="Enter Password"
        onInput={(e) => (password = e.target.value)}/>
      <br /> <br />
      <button onClick={registerUser}> SignUP </button> &nbsp;
      <button onClick={signInUser}> SignIn </button> &nbsp;
      <button onClick={logOutUser}> Logout </button>
      <br />
      <h4> Current User : {CurrentUser} </h4>
    </>
  );
};

//------------------------------------------------------------------------

function App() {
  return (
    <div className="App">
      <SignUp />
    </div>
  );
}

export default App;


Example] In the below example we demonstrate how to perform operations like SignUp, SignIn and Logout using Google Account Authentication.


// firebase-config.js

/* NOTE : You'll get this code snippet when you'll register
 your app inside the firebase project console. */

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

const firebaseConfig = {
  apiKey: "AIzaSyBaed0iaou97bmXAXbJ5RfHb_oKjynB0pQ",
  authDomain: "myreactapp-400c5.firebaseapp.com",
  projectId: "myreactapp-400c5",
  storageBucket: "myreactapp-400c5.appspot.com",
  messagingSenderId: "1087850171665",
  appId: "1:1087850171665:web:2b72554206c0ffec7190b0"
};

export const firebaseApp = initializeApp(firebaseConfig);
export const auth = getAuth(firebaseApp);



// App.js

import "./App.css";
import { useState } from "react";
import { auth } from "./firebase-config";
import {
  signInWithPopup,
  GoogleAuthProvider,
  onAuthStateChanged,
  signOut,
} from "firebase/auth";
const provider = new GoogleAuthProvider();

function App() {
  const [currentUser, setCurrentUser] = useState("None");

  function signInGoogle() {
    signInWithPopup(auth, provider)
      .then((result) => {
       // This gives you Google Access Token. You can use it to access the Google API.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
        // The signed-in user info.
        const user = result.user;
        console.log("signedIn user : ", user);
        // ...
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.customData.email;
        // The AuthCredential type that was used.
        const credential = GoogleAuthProvider.credentialFromError(error);
        // ...
      });
  }


  function signOutUser() {
    signOut(auth)
      .then(() => {
        console.log("User logout sucess !");
      })
      .catch((error) => {
        const errorMessage = error.message;
        console.log("LogOut Error : ", errorMessage);
      });
  }

   // Triggers when user signIn/Out or page refresh.
   onAuthStateChanged(auth, (currentUser) => {
    if (currentUser != null) {
      setCurrentUser(currentUser.email);
      return;
    }
    setCurrentUser("None");
  });

  return (
    <div className="App">
      <h3> SignedIn User : {currentUser}</h3>
      <button onClick={signInGoogle}> SignIn with Google </button>
      <button onClick={signOutUser}> SignOut </button>
    </div>
  );
}

export default App;


---------------------------------------------------------------------------------------------------------------


Firebase Realtime Database

The Firebase Realtime Database is a NoSQL database from which we can store and sync the data between our users in real-time. It is a big JSON object which the developers can manage in real-time. By using a single API, the Firebase database provides the application with the current value of the data and updates to that data. Real-time syncing makes it easy for our users to access their data from any device, be it web or mobile.

Example] In the below example we demonstrate how to perform Write, Update and Delete operations on the realtime database.


// firebase-config.js

/* NOTE : You'll get this code snippet when you'll register
 your app inside the firebase project console. */

import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";

const firebaseConfig = {
  apiKey: "AIzaSyBaed0iaou97bmXAXbJ5RfHb_oKjynB0pQ",
  authDomain: "myreactapp-400c5.firebaseapp.com",
  // Add your database url here
  databaseURL:"https://myreactapp-400c5-default-rtdb.firebaseio.com/",
  projectId: "myreactapp-400c5",
  storageBucket: "myreactapp-400c5.appspot.com",
  messagingSenderId: "1087850171665",
  appId: "1:1087850171665:web:2b72554206c0ffec7190b0"
};


export const firebaseApp = initializeApp(firebaseConfig);
// Get a reference to the database service
export const db = getDatabase(firebaseApp);



// App.js

import "./App.css";
import { ref, set , remove} from "firebase/database";
import { db } from "./firebase-config";

const App=()=> {
 
  function insertStudent() {
    const uname = document.getElementById("uname").value;
    const fname = document.getElementById("fname").value;
    const lname = document.getElementById("lname").value;
    const rollnumber = document.getElementById("rollnumber").value;
    console.log("VALUES : ", fname, lname, rollnumber);

    // Ref of where to insert the data
    const location = ref(db, "students/" + uname);
    const data = {
      username: uname,
      firstname: fname,
      lastname: lname,
      rollnumber: rollnumber,
    };

    try {
      // inser data at "students/username/"
      set(location, data);
    } catch (error) {
      const errorMessage = error.message;
      console.log("Insert Error : ", errorMessage);
    }
  }

  function deleteStudent() {
    // delete the specified username
    const uname = document.getElementById("uname").value;
    const location = ref(db, "students/" + uname);
    try {
      remove(location);
      console.log("Username deleted : ",uname);
    } catch (error) {
      const errorMessage = error.message;
      console.log("Delete Error : ", errorMessage);
    }
  }

  const Home = () => {
    return (
      <>
        <h2> Student Details </h2>
        <input type="text" id="uname" placeholder="Username" /> &nbsp;
        <input type="text" id="fname" placeholder="Firstname" /> &nbsp;
        <input type="text" id="lname" placeholder="Lastname" /> &nbsp;
        <input type="number" id="rollnumber" placeholder="Roll Number" />
        <br /> <br />
        <button onClick={insertStudent}> Insert or Update </button> &nbsp;
        <button onClick={deleteStudent}> Delete </button>
      </>
    );
  };

  return (
    <div className="App">
      <Home />
    </div>
  );
}

export default App;


Example] In the below example we read data from the realtime database.


// App.js

import "./App.css";
import { useState } from "react";
import { ref,get} from "firebase/database";
import { db } from "./firebase-config";

const App=()=> {  

  const [User, setUser] = useState({fname:"None",lname:"None",rollnumber:"None"});

  function getStudentDetails(){
    // Get the details of specified username
    const username = document.getElementById("username_input").value;
    const location = ref(db, `students/${username}`);
    get(location).then((snapshot) => {
      if (snapshot.exists()) {
        const student = snapshot.val();
        // update state
        setUser({fname:student.fname,lname:student.lname,rollnumber:student.roll});
      } else {
        setUser({fname:"None",lname:"None",rollnumber:"None"})
        console.log("Username does'nt exist !");
      }
    }).catch((error) => {
      console.error("Error : ",error);
    });
   
  }

  const Home = () => {
    return (
      <>
        <h2> Student Details </h2>
        <h4> Firstname : {User.fname} </h4>
        <h4> Lastname : {User.lname} </h4>
        <h4> Rollnumber : {User.rollnumber} </h4>
        <input type="text" id="username_input" placeholder="Enter Username" />
        <button onClick={getStudentDetails}> Get Details </button>
      </>
    );
  };

  return (
    <div className="App">
      <Home />
    </div>
  );
}

export default App;


Realtime Updates

One of the main feature provided by firebase is the ability to listen for database changes. We can give ti a reference location to observe and then whenever any data changes , it automatically sends an update to all connected clients. 

Example] In the below example we demonstarte automatic realtime updates using the onValue() event listener function. If you go and manually change the data in the realtime database, then the onValue() triggers and updates the latest values.


// firebase-config.js

/* NOTE : You'll get this code snippet when you'll register
 your app inside the firebase project console. */

import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";

const firebaseConfig = {
  apiKey: "AIzaSyBaed0iaou97bmXAXbJ5RfHb_oKjynB0pQ",
  authDomain: "myreactapp-400c5.firebaseapp.com",
  // Add your database url here
  databaseURL:"https://myreactapp-400c5-default-rtdb.firebaseio.com/",
  projectId: "myreactapp-400c5",
  storageBucket: "myreactapp-400c5.appspot.com",
  messagingSenderId: "1087850171665",
  appId: "1:1087850171665:web:2b72554206c0ffec7190b0"
};


export const firebaseApp = initializeApp(firebaseConfig);
// Get a reference to the database service
export const db = getDatabase(firebaseApp);



// App.js

import "./App.css";
import { ref, onValue } from "firebase/database";
import { db } from "./firebase-config";

const App = () => {

  // Location to observe for changes in database
  const location = ref(db, "students/deepeshdm");

  // Triggers whenever value at given location changes.
  onValue(location,(snapshot)=>{
    console.log("onValue() called !")
    if (snapshot.exists()) {
      // Get the latest values
      const student = snapshot.val();
      console.log(student)
      // Update the display values
      let fname = document.getElementById("fname");
      let lname = document.getElementById("lname");
      let rollnumber = document.getElementById("rollnumber");
      fname.innerHTML = "Firstname : "+student.fname;
      lname.innerHTML = "Lastname : "+student.lname;
      rollnumber.innerHTML = "Rollnumber : "+student.roll;
    } else {
      console.log("Given username does'nt exist !");
    }
  })

  const Home = () => {
    return (
      <>
        <h2> Student Details </h2>
        <h4 id="fname"> Firstname :  </h4>
        <h4 id="lname"> Lastname :  </h4>
        <h4 id="rollnumber"> Rollnumber :  </h4>
      </>
    );
  };

  return (
    <div className="App">
      <Home />
    </div>
  );
};

export default App;



Firebase Firestore

Cloud Firestore is a NoSQL document database that lets you easily store, sync, and query data for your mobile and web apps - at global scale.  It is used to store and sync data for client and server-side development. It is used for mobile, web, and server development from Google Cloud Platform and Firebase. Like the Firebase Real-time Database, it keeps syncing our data via real-time listeners to the client app. 

Example] In the below example we demonstrate how to perform Write, Update and Delete operations on the firestore database.


// firebase-config.js

/* NOTE : You'll get this code snippet when you'll register
 your app inside the firebase project console. */

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey: "AIzaSyBaed0iaou97bmXAXbJ5RfHb_oKjynB0pQ",
  authDomain: "myreactapp-400c5.firebaseapp.com",
  projectId: "myreactapp-400c5",
  storageBucket: "myreactapp-400c5.appspot.com",
  messagingSenderId: "1087850171665",
  appId: "1:1087850171665:web:2b72554206c0ffec7190b0"
};


export const firebaseApp = initializeApp(firebaseConfig);
// Initialize Cloud Firestore and get a reference to the service
export const db = getFirestore(firebaseApp);



// App.Js

import "./App.css";
import { doc, setDoc , deleteDoc } from "firebase/firestore";
import { db } from "./firebase-config";

const App=()=> {
 
async function insertStudent() {
    const uname = document.getElementById("uname").value;
    const fname = document.getElementById("fname").value;
    const lname = document.getElementById("lname").value;
    const rollnumber = document.getElementById("rollnumber").value;
    console.log("VALUES : ", fname, lname, rollnumber);

    // Ref of where to insert the data
    const location = doc(db, "users",uname)
    const data = {
      username: uname,
      firstname: fname,
      lastname: lname,
      rollnumber: rollnumber,
    };

    try {
      await setDoc(location, data);
      console.log("Data inserted !")
    } catch (error) {
      const errorMessage = error.message;
      console.log("Insert Error : ", errorMessage);
    }
  }

  async function deleteStudent() {
    // delete the specified username
    const uname = document.getElementById("uname").value;
    const location = doc(db, "users",uname)
    try {
      await deleteDoc(location);
      console.log("Username deleted : ",uname);
    } catch (error) {
      const errorMessage = error.message;
      console.log("Delete Error : ", errorMessage);
    }
  }

  const Home = () => {
    return (
      <>
        <h2> Student Details </h2>
        <input type="text" id="uname" placeholder="Username" /> &nbsp;
        <input type="text" id="fname" placeholder="Firstname" /> &nbsp;
        <input type="text" id="lname" placeholder="Lastname" /> &nbsp;
        <input type="number" id="rollnumber" placeholder="Roll Number" />
        <br /> <br />
        <button onClick={insertStudent}> Insert or Update </button> &nbsp;
        <button onClick={deleteStudent}> Delete </button>
      </>
    );
  };

  return (
    <div className="App">
      <Home />
    </div>
  );
}

export default App;


Example] In the below example we read data from the firestore database.

                         


// App.jS

import "./App.css";
import { useState } from "react";
import { doc, getDoc } from "firebase/firestore";
import { db } from "./firebase-config";

const App=()=> {  

  const [User, setUser] = useState({fname:"None",lname:"None",rollnumber:"None"});

  async function getStudentDetails(){
    // Get the details of specified username
    const username = document.getElementById("username_input").value;
    const location = doc(db, "users",username)
    const snapshot = await getDoc(location);
    if (snapshot.exists()) {
      const student = snapshot.data();
      // update state
      setUser({fname:student.firstname,lname:student.lastname,
rollnumber:student.rollnumber});
    } else {
      setUser({fname:"None",lname:"None",rollnumber:"None"})
      console.log("Username does'nt exist !");
    }
   
  }

  const Home = () => {
    return (
      <>
        <h2> Student Details </h2>
        <h4> Firstname : {User.fname} </h4>
        <h4> Lastname : {User.lname} </h4>
        <h4> Rollnumber : {User.rollnumber} </h4>
        <input type="text" id="username_input" placeholder="Enter Username" />
        <button onClick={getStudentDetails}> Get Details </button>
      </>
    );
  };

  return (
    <div className="App">
      <Home />
    </div>
  );
}

export default App;


Example] In the below example we demonstarte automatic realtime updates using the onSnapshot() event listener function. If you go and manually change the data in the realtime database, then the onSnapshot() triggers and updates the latest values.

                        


 // App.js

 import "./App.css";
 import { doc, onSnapshot } from "firebase/firestore";
 import { db } from "./firebase-config";
 
 const App = () => {
 
   // Location to observe for changes in database
   const location = doc(db, "users","deepeshdm")

   // Triggers whenever value at given location changes.
   onSnapshot(location, (doc) => {
    if (doc) {
      // Get the latest values
      const student = doc.data();
      console.log(student)
      // Update the display values
      let fname = document.getElementById("fname");
      let lname = document.getElementById("lname");
      let rollnumber = document.getElementById("rollnumber");
      fname.innerHTML = "Firstname : "+student.firstname;
      lname.innerHTML = "Lastname : "+student.lastname;
      rollnumber.innerHTML = "Rollnumber : "+student.rollnumber;
    }

});
 
 
   const Home = () => {
     return (
       <>
         <h2> Student Details </h2>
         <h4 id="fname"> Firstname :  </h4>
         <h4 id="lname"> Lastname :  </h4>
         <h4 id="rollnumber"> Rollnumber :  </h4>
       </>
     );
   };
 
   return (
     <div className="App">
       <Home />
     </div>
   );
 };
 
 export default App;
 


---------------------------------------------------------------------------------------------------------------




Comments

Popular posts from this blog

React Js + React-Redux (part-2)

React Js + CSS Styling + React Router (part-1)

ViteJS (Module Bundlers, Build Tools)