Firebase
Platform
Firebase
Overview
Firebase is a comprehensive BaaS (Backend-as-a-Service) platform provided by Google for mobile and web development. It integrates authentication, real-time database, cloud storage, hosting, and analytics features, enabling developers to quickly build scalable applications. Widely adopted as the de facto standard for mobile app development, it's used across a broad range from startups to large enterprises. Deep integration with Google Cloud Platform provides enterprise-level functionality and scalability.
Details
Firebase 2025 continues to revolutionize modern app development with a mobile-first approach. With over 15 years of development experience and leveraging Google's infrastructure, it supports millions of applications worldwide. The rich service suite including Real-time Database, Cloud Firestore, Cloud Functions, Firebase Auth, and Cloud Storage provides an environment where developers can focus on frontend development. Advanced features like Machine Learning Kit, Performance Monitoring, and Crashlytics enable app quality improvement and operational efficiency. Additionally, it provides unified SDKs for all platforms including Flutter, React Native, iOS, Android, and Web, strongly supporting cross-platform development.
Key Features
- Real-time Database: WebSocket-based real-time synchronization
- Cloud Firestore: NoSQL document database
- Firebase Auth: Comprehensive authentication system
- Cloud Storage: Scalable file storage
- Firebase Hosting: High-speed web hosting
- Cloud Functions: Serverless function execution environment
Advantages and Disadvantages
Advantages
- High availability and scalability through Google's global infrastructure
- Significant development speed improvement through comprehensive BaaS solutions
- Excellent user experience through real-time capabilities
- Reduced learning costs through rich SDKs and documentation
- Enterprise support through Google Cloud Platform integration
- Flexible pricing from free to enterprise plans
Disadvantages
- Vendor lock-in risk and platform dependency
- High costs and unpredictable pricing for large-scale usage
- Learning costs for RDBMS-experienced developers due to NoSQL base
- Limitations in complex queries and aggregation processing
- Limited customization possibilities and difficulty addressing unique requirements
- Technical challenges during data export or migration
Reference Links
Code Examples
Setup and Initialization
# Install Firebase CLI
npm install -g firebase-tools
# Initialize Firebase project
firebase login
firebase init
# Install Firebase SDK (Web)
npm install firebase
// Firebase initialization (Web)
import { initializeApp } from 'firebase/app';
import { getAnalytics } from 'firebase/analytics';
const firebaseConfig = {
apiKey: "your-api-key",
authDomain: "your-project.firebaseapp.com",
projectId: "your-project-id",
storageBucket: "your-project.appspot.com",
messagingSenderId: "123456789",
appId: "1:123456789:web:abc123def456"
};
// Initialize Firebase app
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
console.log('Firebase initialized successfully');
Authentication System
import {
getAuth,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signInWithPopup,
GoogleAuthProvider,
onAuthStateChanged,
signOut
} from 'firebase/auth';
const auth = getAuth();
const googleProvider = new GoogleAuthProvider();
// User registration
async function signUp(email, password) {
try {
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
const user = userCredential.user;
console.log('User registered:', user.uid);
return user;
} catch (error) {
console.error('Sign up error:', error.code, error.message);
throw error;
}
}
// Sign in with email/password
async function signIn(email, password) {
try {
const userCredential = await signInWithEmailAndPassword(auth, email, password);
const user = userCredential.user;
console.log('User signed in:', user.uid);
return user;
} catch (error) {
console.error('Sign in error:', error.code, error.message);
throw error;
}
}
// Sign in with Google account
async function signInWithGoogle() {
try {
const result = await signInWithPopup(auth, googleProvider);
const user = result.user;
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
console.log('Google sign in successful:', user.displayName);
return { user, token };
} catch (error) {
console.error('Google sign in error:', error.code, error.message);
throw error;
}
}
// Monitor authentication state
onAuthStateChanged(auth, (user) => {
if (user) {
console.log('User is signed in:', user.uid);
// User is logged in
displayUserProfile(user);
} else {
console.log('User is signed out');
// User is logged out
displayLoginForm();
}
});
// Sign out
async function handleSignOut() {
try {
await signOut(auth);
console.log('User signed out successfully');
} catch (error) {
console.error('Sign out error:', error);
}
}
// Display user profile
function displayUserProfile(user) {
document.getElementById('user-info').innerHTML = `
<h3>Welcome, ${user.displayName || user.email}</h3>
<p>UID: ${user.uid}</p>
<p>Email: ${user.email}</p>
<p>Email Verified: ${user.emailVerified}</p>
<button onclick="handleSignOut()">Sign Out</button>
`;
}
Database Operations (Cloud Firestore)
import {
getFirestore,
collection,
doc,
addDoc,
getDoc,
getDocs,
updateDoc,
deleteDoc,
query,
where,
orderBy,
limit,
onSnapshot
} from 'firebase/firestore';
const db = getFirestore();
// Add document
async function addUser(userData) {
try {
const docRef = await addDoc(collection(db, 'users'), {
name: userData.name,
email: userData.email,
age: userData.age,
createdAt: new Date(),
isActive: true
});
console.log('User added with ID:', docRef.id);
return docRef.id;
} catch (error) {
console.error('Error adding user:', error);
throw error;
}
}
// Get document
async function getUser(userId) {
try {
const docRef = doc(db, 'users', userId);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log('User data:', docSnap.data());
return { id: docSnap.id, ...docSnap.data() };
} else {
console.log('No such user found');
return null;
}
} catch (error) {
console.error('Error getting user:', error);
throw error;
}
}
// Get entire collection
async function getAllUsers() {
try {
const querySnapshot = await getDocs(collection(db, 'users'));
const users = [];
querySnapshot.forEach((doc) => {
users.push({ id: doc.id, ...doc.data() });
});
console.log('All users:', users);
return users;
} catch (error) {
console.error('Error getting users:', error);
throw error;
}
}
// Query-based search
async function getActiveUsers() {
try {
const q = query(
collection(db, 'users'),
where('isActive', '==', true),
orderBy('createdAt', 'desc'),
limit(10)
);
const querySnapshot = await getDocs(q);
const activeUsers = [];
querySnapshot.forEach((doc) => {
activeUsers.push({ id: doc.id, ...doc.data() });
});
console.log('Active users:', activeUsers);
return activeUsers;
} catch (error) {
console.error('Error getting active users:', error);
throw error;
}
}
// Real-time update monitoring
function listenToUsers() {
const q = query(collection(db, 'users'), orderBy('createdAt', 'desc'));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
const users = [];
querySnapshot.forEach((doc) => {
users.push({ id: doc.id, ...doc.data() });
});
console.log('Real-time users update:', users);
updateUserList(users);
}, (error) => {
console.error('Error listening to users:', error);
});
// To unsubscribe the listener
// unsubscribe();
return unsubscribe;
}
// Update document
async function updateUser(userId, updates) {
try {
const userRef = doc(db, 'users', userId);
await updateDoc(userRef, {
...updates,
updatedAt: new Date()
});
console.log('User updated successfully');
} catch (error) {
console.error('Error updating user:', error);
throw error;
}
}
File Storage
import {
getStorage,
ref,
uploadBytes,
uploadBytesResumable,
getDownloadURL,
deleteObject,
listAll
} from 'firebase/storage';
const storage = getStorage();
// File upload
async function uploadFile(file, path) {
try {
const storageRef = ref(storage, path);
const snapshot = await uploadBytes(storageRef, file);
console.log('File uploaded successfully');
// Get download URL
const downloadURL = await getDownloadURL(snapshot.ref);
console.log('Download URL:', downloadURL);
return { downloadURL, fullPath: snapshot.ref.fullPath };
} catch (error) {
console.error('Error uploading file:', error);
throw error;
}
}
// File upload with progress
function uploadFileWithProgress(file, path, onProgress) {
return new Promise((resolve, reject) => {
const storageRef = ref(storage, path);
const uploadTask = uploadBytesResumable(storageRef, file);
uploadTask.on(
'state_changed',
(snapshot) => {
// Calculate progress
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload progress:', progress + '%');
if (onProgress) {
onProgress(progress, snapshot);
}
switch (snapshot.state) {
case 'paused':
console.log('Upload is paused');
break;
case 'running':
console.log('Upload is running');
break;
}
},
(error) => {
console.error('Upload error:', error);
reject(error);
},
async () => {
// Upload completed
try {
const downloadURL = await getDownloadURL(uploadTask.snapshot.ref);
console.log('File available at:', downloadURL);
resolve({
downloadURL,
fullPath: uploadTask.snapshot.ref.fullPath,
metadata: uploadTask.snapshot.metadata
});
} catch (urlError) {
reject(urlError);
}
}
);
});
}
// Delete file
async function deleteFile(filePath) {
try {
const fileRef = ref(storage, filePath);
await deleteObject(fileRef);
console.log('File deleted successfully');
} catch (error) {
console.error('Error deleting file:', error);
throw error;
}
}
// List files in directory
async function listFiles(directoryPath) {
try {
const listRef = ref(storage, directoryPath);
const result = await listAll(listRef);
const files = await Promise.all(
result.items.map(async (itemRef) => {
const downloadURL = await getDownloadURL(itemRef);
return {
name: itemRef.name,
fullPath: itemRef.fullPath,
downloadURL
};
})
);
console.log('Files in directory:', files);
return files;
} catch (error) {
console.error('Error listing files:', error);
throw error;
}
}
Real-time Features
import {
getDatabase,
ref as dbRef,
push,
set,
get,
onValue,
off,
serverTimestamp,
remove
} from 'firebase/database';
const realtimeDb = getDatabase();
// Real-time chat implementation
class RealtimeChat {
constructor(roomId) {
this.roomId = roomId;
this.messagesRef = dbRef(realtimeDb, `chats/${roomId}/messages`);
this.usersRef = dbRef(realtimeDb, `chats/${roomId}/users`);
}
// Send message
async sendMessage(userId, userName, message) {
try {
const messageData = {
userId,
userName,
message,
timestamp: serverTimestamp()
};
await push(this.messagesRef, messageData);
console.log('Message sent successfully');
} catch (error) {
console.error('Error sending message:', error);
throw error;
}
}
// Listen to messages in real-time
listenToMessages(callback) {
onValue(this.messagesRef, (snapshot) => {
const messages = [];
snapshot.forEach((child) => {
messages.push({
id: child.key,
...child.val()
});
});
// Sort by timestamp
messages.sort((a, b) => (a.timestamp || 0) - (b.timestamp || 0));
callback(messages);
});
}
// Manage user online status
async setUserOnline(userId, userName) {
try {
const userRef = dbRef(realtimeDb, `chats/${this.roomId}/users/${userId}`);
await set(userRef, {
name: userName,
online: true,
lastSeen: serverTimestamp()
});
// Handle when user goes offline
const offlineRef = dbRef(realtimeDb, `chats/${this.roomId}/users/${userId}/online`);
await set(offlineRef, false);
} catch (error) {
console.error('Error setting user online:', error);
}
}
// Listen to online users
listenToOnlineUsers(callback) {
onValue(this.usersRef, (snapshot) => {
const users = [];
snapshot.forEach((child) => {
const userData = child.val();
if (userData.online) {
users.push({
id: child.key,
...userData
});
}
});
callback(users);
});
}
// Stop listeners
stopListening() {
off(this.messagesRef);
off(this.usersRef);
}
}
// Chat usage example
const chat = new RealtimeChat('room123');
// Start message listening
chat.listenToMessages((messages) => {
console.log('New messages:', messages);
displayMessages(messages);
});
// Start online users listening
chat.listenToOnlineUsers((users) => {
console.log('Online users:', users);
displayOnlineUsers(users);
});
// Set user online
chat.setUserOnline('user123', 'John Doe');
// Send message
document.getElementById('send-button').addEventListener('click', () => {
const messageInput = document.getElementById('message-input');
const message = messageInput.value.trim();
if (message) {
chat.sendMessage('user123', 'John Doe', message);
messageInput.value = '';
}
});
Deployment and Production Operations
# Deploy with Firebase Hosting
firebase init hosting
firebase deploy
# Deploy specific services only
firebase deploy --only hosting
firebase deploy --only functions
firebase deploy --only firestore:rules
# Deploy Cloud Functions
firebase init functions
cd functions
npm install
cd ..
firebase deploy --only functions
# Deploy security rules
firebase deploy --only firestore:rules,storage
// Firestore Security Rules example (firestore.rules)
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Users can only access their own documents
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
// Public posts are readable by authenticated users, editable only by author
match /posts/{postId} {
allow read: if request.auth != null;
allow write: if request.auth != null &&
(resource == null || resource.data.authorId == request.auth.uid);
}
// Chat messages accessible only to participants
match /chats/{chatId}/messages/{messageId} {
allow read, write: if request.auth != null &&
request.auth.uid in get(/databases/$(database)/documents/chats/$(chatId)).data.participants;
}
}
}
// Performance Monitoring setup
import { getPerformance, trace } from 'firebase/performance';
const perf = getPerformance();
// Create custom trace
const customTrace = trace(perf, 'data_loading');
customTrace.start();
try {
// Data loading process
const data = await fetchImportantData();
customTrace.putAttribute('data_size', data.length.toString());
customTrace.putMetric('items_loaded', data.length);
} catch (error) {
customTrace.putAttribute('error', error.message);
} finally {
customTrace.stop();
}
// Send Analytics events
import { getAnalytics, logEvent } from 'firebase/analytics';
const analytics = getAnalytics();
// Send custom event
logEvent(analytics, 'user_engagement', {
action: 'button_click',
page: 'home',
user_id: currentUser.uid
});
// E-commerce event example
logEvent(analytics, 'purchase', {
transaction_id: 'T12345',
value: 25.42,
currency: 'USD',
items: [{
item_id: 'SKU123',
item_name: 'Example Product',
category: 'Electronics',
price: 25.42,
quantity: 1
}]
});