-
Notifications
You must be signed in to change notification settings - Fork 0
API Reference
ThanuMahee12 edited this page Oct 19, 2025
·
1 revision
Complete reference for Firebase Authentication, Firestore, and Storage APIs used in this template.
import { getAuth } from 'firebase/auth'
import app from './config'
export const auth = getAuth(app)import { createUserWithEmailAndPassword, updateProfile } from 'firebase/auth'
const signUp = async (email, password, displayName) => {
try {
const userCredential = await createUserWithEmailAndPassword(auth, email, password)
// Update profile
await updateProfile(userCredential.user, { displayName })
return { user: userCredential.user, error: null }
} catch (error) {
return { user: null, error: error.message }
}
}import { signInWithEmailAndPassword } from 'firebase/auth'
const signIn = async (email, password) => {
try {
const userCredential = await signInWithEmailAndPassword(auth, email, password)
return { user: userCredential.user, error: null }
} catch (error) {
return { user: null, error: error.message }
}
}import { GoogleAuthProvider, signInWithPopup } from 'firebase/auth'
const signInWithGoogle = async () => {
try {
const provider = new GoogleAuthProvider()
const userCredential = await signInWithPopup(auth, provider)
return { user: userCredential.user, error: null }
} catch (error) {
return { user: null, error: error.message }
}
}import { signOut } from 'firebase/auth'
const logOut = async () => {
try {
await signOut(auth)
return { error: null }
} catch (error) {
return { error: error.message }
}
}import { sendEmailVerification } from 'firebase/auth'
const sendVerificationEmail = async () => {
try {
await sendEmailVerification(auth.currentUser)
return { error: null }
} catch (error) {
return { error: error.message }
}
}import { sendPasswordResetEmail } from 'firebase/auth'
const resetPassword = async (email) => {
try {
await sendPasswordResetEmail(auth, email)
return { error: null }
} catch (error) {
return { error: error.message }
}
}import { updateProfile } from 'firebase/auth'
const updateUserProfile = async (updates) => {
try {
await updateProfile(auth.currentUser, updates)
return { error: null }
} catch (error) {
return { error: error.message }
}
}
// Usage
await updateUserProfile({
displayName: 'John Doe',
photoURL: 'https://example.com/photo.jpg'
})import { onAuthStateChanged } from 'firebase/auth'
onAuthStateChanged(auth, (user) => {
if (user) {
console.log('User is signed in:', user)
} else {
console.log('User is signed out')
}
})const getCurrentUser = () => {
return auth.currentUser
}import { deleteUser } from 'firebase/auth'
const deleteAccount = async () => {
try {
await deleteUser(auth.currentUser)
return { error: null }
} catch (error) {
return { error: error.message }
}
}import { getFirestore } from 'firebase/firestore'
import app from './config'
export const db = getFirestore(app)import { collection, addDoc, doc, setDoc, serverTimestamp } from 'firebase/firestore'
// Auto-generated ID
const createDocument = async (collectionName, data) => {
try {
const docRef = await addDoc(collection(db, collectionName), {
...data,
createdAt: serverTimestamp()
})
return { id: docRef.id, error: null }
} catch (error) {
return { id: null, error: error.message }
}
}
// Custom ID
const createDocumentWithId = async (collectionName, docId, data) => {
try {
await setDoc(doc(db, collectionName, docId), {
...data,
createdAt: serverTimestamp()
})
return { error: null }
} catch (error) {
return { error: error.message }
}
}import { doc, getDoc } from 'firebase/firestore'
const getDocument = async (collectionName, docId) => {
try {
const docSnap = await getDoc(doc(db, collectionName, docId))
if (docSnap.exists()) {
return { data: { id: docSnap.id, ...docSnap.data() }, error: null }
} else {
return { data: null, error: 'Document not found' }
}
} catch (error) {
return { data: null, error: error.message }
}
}import { collection, getDocs } from 'firebase/firestore'
const getAllDocuments = async (collectionName) => {
try {
const querySnapshot = await getDocs(collection(db, collectionName))
const documents = querySnapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}))
return { data: documents, error: null }
} catch (error) {
return { data: null, error: error.message }
}
}import { collection, query, where, getDocs, orderBy, limit } from 'firebase/firestore'
const queryDocuments = async (collectionName, conditions = []) => {
try {
let q = collection(db, collectionName)
// Apply conditions
conditions.forEach(condition => {
q = query(q, where(condition.field, condition.operator, condition.value))
})
const querySnapshot = await getDocs(q)
const documents = querySnapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}))
return { data: documents, error: null }
} catch (error) {
return { data: null, error: error.message }
}
}
// Usage
const users = await queryDocuments('users', [
{ field: 'age', operator: '>=', value: 18 },
{ field: 'status', operator: '==', value: 'active' }
])import { doc, updateDoc } from 'firebase/firestore'
const updateDocument = async (collectionName, docId, data) => {
try {
await updateDoc(doc(db, collectionName, docId), data)
return { error: null }
} catch (error) {
return { error: error.message }
}
}import { doc, deleteDoc } from 'firebase/firestore'
const deleteDocument = async (collectionName, docId) => {
try {
await deleteDoc(doc(db, collectionName, docId))
return { error: null }
} catch (error) {
return { error: error.message }
}
}import { doc, onSnapshot } from 'firebase/firestore'
const listenToDocument = (collectionName, docId, callback) => {
const unsubscribe = onSnapshot(
doc(db, collectionName, docId),
(docSnap) => {
if (docSnap.exists()) {
callback({ id: docSnap.id, ...docSnap.data() })
}
},
(error) => {
console.error('Error listening to document:', error)
}
)
return unsubscribe // Call this to stop listening
}
// Usage
const unsubscribe = listenToDocument('users', userId, (user) => {
console.log('User updated:', user)
})
// Later: unsubscribe()import { writeBatch, doc } from 'firebase/firestore'
const batchWrite = async (operations) => {
try {
const batch = writeBatch(db)
operations.forEach(op => {
const docRef = doc(db, op.collection, op.id)
if (op.type === 'set') {
batch.set(docRef, op.data)
} else if (op.type === 'update') {
batch.update(docRef, op.data)
} else if (op.type === 'delete') {
batch.delete(docRef)
}
})
await batch.commit()
return { error: null }
} catch (error) {
return { error: error.message }
}
}
// Usage
await batchWrite([
{ type: 'set', collection: 'users', id: 'user1', data: { name: 'John' } },
{ type: 'update', collection: 'posts', id: 'post1', data: { likes: 10 } },
{ type: 'delete', collection: 'comments', id: 'comment1' }
])import { collection, query, orderBy, limit, startAfter, getDocs } from 'firebase/firestore'
const getPaginatedDocuments = async (collectionName, pageSize = 10, lastDoc = null) => {
try {
let q = query(
collection(db, collectionName),
orderBy('createdAt', 'desc'),
limit(pageSize)
)
if (lastDoc) {
q = query(q, startAfter(lastDoc))
}
const querySnapshot = await getDocs(q)
const documents = querySnapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}))
const last = querySnapshot.docs[querySnapshot.docs.length - 1]
return {
data: documents,
lastDoc: last,
hasMore: documents.length === pageSize,
error: null
}
} catch (error) {
return { data: null, lastDoc: null, hasMore: false, error: error.message }
}
}
// Usage
const page1 = await getPaginatedDocuments('posts', 10)
const page2 = await getPaginatedDocuments('posts', 10, page1.lastDoc)import { getStorage } from 'firebase/storage'
import app from './config'
export const storage = getStorage(app)import { ref, uploadBytes, getDownloadURL } from 'firebase/storage'
const uploadFile = async (file, path) => {
try {
const storageRef = ref(storage, path)
const snapshot = await uploadBytes(storageRef, file)
const url = await getDownloadURL(snapshot.ref)
return { url, error: null }
} catch (error) {
return { url: null, error: error.message }
}
}
// Usage
const { url } = await uploadFile(file, `images/${userId}/${Date.now()}.jpg`)import { ref, uploadBytesResumable, getDownloadURL } from 'firebase/storage'
const uploadFileWithProgress = (file, path, onProgress) => {
return new Promise((resolve, reject) => {
const storageRef = ref(storage, path)
const uploadTask = uploadBytesResumable(storageRef, file)
uploadTask.on(
'state_changed',
(snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
onProgress(progress)
},
(error) => reject(error),
async () => {
const url = await getDownloadURL(uploadTask.snapshot.ref)
resolve(url)
}
)
})
}
// Usage
const url = await uploadFileWithProgress(
file,
`images/${userId}/photo.jpg`,
(progress) => console.log(`Upload is ${progress}% done`)
)import { ref, getDownloadURL } from 'firebase/storage'
const getFileUrl = async (path) => {
try {
const storageRef = ref(storage, path)
const url = await getDownloadURL(storageRef)
return { url, error: null }
} catch (error) {
return { url: null, error: error.message }
}
}import { ref, deleteObject } from 'firebase/storage'
const deleteFile = async (path) => {
try {
const storageRef = ref(storage, path)
await deleteObject(storageRef)
return { error: null }
} catch (error) {
return { error: error.message }
}
}import { ref, listAll } from 'firebase/storage'
const listFiles = async (path) => {
try {
const storageRef = ref(storage, path)
const result = await listAll(storageRef)
const files = result.items.map(item => ({
name: item.name,
fullPath: item.fullPath
}))
return { files, error: null }
} catch (error) {
return { files: null, error: error.message }
}
}// Create user profile after signup
const createUserProfile = async (userId, userData) => {
await setDoc(doc(db, 'users', userId), {
...userData,
createdAt: serverTimestamp()
})
}
// Get user profile
const getUserProfile = async (userId) => {
const docSnap = await getDoc(doc(db, 'users', userId))
return docSnap.exists() ? docSnap.data() : null
}
// Update user profile
const updateUserProfile = async (userId, updates) => {
await updateDoc(doc(db, 'users', userId), updates)
}class FirestoreService {
constructor(collectionName) {
this.collectionName = collectionName
}
async create(data) {
const docRef = await addDoc(collection(db, this.collectionName), {
...data,
createdAt: serverTimestamp()
})
return docRef.id
}
async read(id) {
const docSnap = await getDoc(doc(db, this.collectionName, id))
return docSnap.exists() ? { id: docSnap.id, ...docSnap.data() } : null
}
async update(id, data) {
await updateDoc(doc(db, this.collectionName, id), data)
}
async delete(id) {
await deleteDoc(doc(db, this.collectionName, id))
}
async getAll() {
const querySnapshot = await getDocs(collection(db, this.collectionName))
return querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }))
}
}
// Usage
const postsService = new FirestoreService('posts')
await postsService.create({ title: 'Hello', content: 'World' })const handleAuthError = (errorCode) => {
const errors = {
'auth/email-already-in-use': 'This email is already registered',
'auth/invalid-email': 'Invalid email address',
'auth/weak-password': 'Password should be at least 6 characters',
'auth/user-not-found': 'No user found with this email',
'auth/wrong-password': 'Incorrect password',
'auth/too-many-requests': 'Too many failed attempts. Try again later'
}
return errors[errorCode] || 'An error occurred. Please try again'
}Next: Best Practices →
Firebase React Template | Made with ❤️ | GitHub | Report Issues
Getting Started
Configuration
Advanced Topics
Deployment
- React 19
- Vite
- Firebase 12
- Redux Toolkit
- React Router