Introduction to Firebase
Firebase is a powerful platform provided by Google that offers a wide array of tools and services to help you develop high-quality apps with ease. It supports backend services such as real-time databases, cloud storage, authentication, and many other features that can improve the efficiency and scalability of your projects.
Firebase Authentication
Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users in your app. It supports authentication using passwords, phone numbers, popular identity providers like Google, Facebook, and Twitter, and more.
// Initialize Firebase Authentication import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth"; const auth = getAuth(); const provider = new GoogleAuthProvider(); signInWithPopup(auth, provider) .then((result) => { const user = result.user; console.log('User signed in: ', user.displayName); }) .catch((error) => { console.error('Error during sign-in:', error); });
Firestore Database
Firestore is a flexible, scalable database for mobile, web, and server development. Cloud Firestore keeps your data in sync across client apps through real-time listeners and offers offline support for mobile and web, so you can build responsive apps that work regardless of network latency or Internet connectivity.
import { getFirestore, collection, addDoc, getDocs } from "firebase/firestore"; const db = getFirestore(); const usersCollection = collection(db, "users"); // Add a new document with a generated id. const addUser = async (user) => { try { const docRef = await addDoc(usersCollection, user); console.log("Document written with ID: ", docRef.id); } catch (e) { console.error("Error adding document: ", e); } }; // Get all users const getUsers = async () => { const querySnapshot = await getDocs(usersCollection); querySnapshot.forEach((doc) => { console.log(`${doc.id} => ${doc.data()}`); }); };
Firebase Storage
Firebase Storage provides a powerful, simple, and cost-effective object storage service built for Google scale. Firebase Storage allows you to upload and store user-generated content such as photos and videos.
import { getStorage, ref, uploadBytes, getDownloadURL } from "firebase/storage"; const storage = getStorage(); const storageRef = ref(storage, 'some-child'); // Upload file const uploadFile = (file) => { uploadBytes(storageRef, file).then((snapshot) => { console.log('Uploaded a blob or file!', snapshot); }); }; // Download file URL const downloadFileURL = async () => { const url = await getDownloadURL(storageRef); console.log('File available at', url); };
Example App Using Firebase APIs
Below is an example of a simple app utilizing Firebase Authentication, Firestore Database, and Firebase Storage.
import { initializeApp } from "firebase/app"; import { getAuth, onAuthStateChanged, signInWithPopup, GoogleAuthProvider } from "firebase/auth"; import { getFirestore, collection, addDoc, getDocs } from "firebase/firestore"; import { getStorage, ref, uploadBytes, getDownloadURL } from "firebase/storage"; const firebaseConfig = { apiKey: "...", authDomain: "...", projectId: "...", storageBucket: "...", messagingSenderId: "...", appId: "..." }; // Initialize Firebase const app = initializeApp(firebaseConfig); const auth = getAuth(); const db = getFirestore(app); const storage = getStorage(app); const provider = new GoogleAuthProvider(); // Sign in and get user data const signIn = () => { signInWithPopup(auth, provider).then((result) => { const user = result.user; console.log('User signed in: ', user); // Save user to Firestore addDoc(collection(db, "users"), { uid: user.uid, name: user.displayName, email: user.email }); }).catch((error) => { console.error('Error during sign-in: ', error); }); }; // Upload file to Firebase Storage const uploadFile = (file) => { const storageRef = ref(storage, 'uploads/' + file.name); uploadBytes(storageRef, file).then((snapshot) => { console.log('File uploaded!', snapshot.metadata); // Get download URL getDownloadURL(storageRef).then((url) => { console.log('File available at', url); }); }); }; // Fetch all users from Firestore const fetchUsers = async () => { const querySnapshot = await getDocs(collection(db, "users")); querySnapshot.forEach((doc) => { console.log(`${doc.id} => ${doc.data()}`); }); }; // Example usage onAuthStateChanged(auth, (user) => { if (user) { console.log('User is signed in: ', user); } else { console.log('No user is signed in'); } }); // Call functions as needed signIn(); // Assume 'file' is a file object from input // uploadFile(file); fetchUsers();