Skip to content

API Reference

ThanuMahee12 edited this page Oct 19, 2025 · 1 revision

API Reference

Complete reference for Firebase Authentication, Firestore, and Storage APIs used in this template.

Table of Contents


Authentication API

Initialize Auth

import { getAuth } from 'firebase/auth'
import app from './config'

export const auth = getAuth(app)

Sign Up with Email/Password

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 }
  }
}

Sign In with Email/Password

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 }
  }
}

Sign In with Google

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 }
  }
}

Sign Out

import { signOut } from 'firebase/auth'

const logOut = async () => {
  try {
    await signOut(auth)
    return { error: null }
  } catch (error) {
    return { error: error.message }
  }
}

Send Email Verification

import { sendEmailVerification } from 'firebase/auth'

const sendVerificationEmail = async () => {
  try {
    await sendEmailVerification(auth.currentUser)
    return { error: null }
  } catch (error) {
    return { error: error.message }
  }
}

Send Password Reset Email

import { sendPasswordResetEmail } from 'firebase/auth'

const resetPassword = async (email) => {
  try {
    await sendPasswordResetEmail(auth, email)
    return { error: null }
  } catch (error) {
    return { error: error.message }
  }
}

Update Profile

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'
})

Listen to Auth State Changes

import { onAuthStateChanged } from 'firebase/auth'

onAuthStateChanged(auth, (user) => {
  if (user) {
    console.log('User is signed in:', user)
  } else {
    console.log('User is signed out')
  }
})

Get Current User

const getCurrentUser = () => {
  return auth.currentUser
}

Delete User Account

import { deleteUser } from 'firebase/auth'

const deleteAccount = async () => {
  try {
    await deleteUser(auth.currentUser)
    return { error: null }
  } catch (error) {
    return { error: error.message }
  }
}

Firestore API

Initialize Firestore

import { getFirestore } from 'firebase/firestore'
import app from './config'

export const db = getFirestore(app)

Create Document

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 }
  }
}

Read Document

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 }
  }
}

Read All Documents

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 }
  }
}

Query Documents

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' }
])

Update Document

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 }
  }
}

Delete Document

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 }
  }
}

Real-time Listener

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()

Batch Operations

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' }
])

Pagination

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)

Storage API

Initialize Storage

import { getStorage } from 'firebase/storage'
import app from './config'

export const storage = getStorage(app)

Upload File

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`)

Upload with Progress

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`)
)

Download File

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 }
  }
}

Delete File

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 }
  }
}

List Files

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 }
  }
}

Common Patterns

User Profile Management

// 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)
}

CRUD Operations Helper

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' })

Error Handling

Common Error Codes

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

📖 Documentation

Getting Started

Configuration

Advanced Topics

Deployment


🔗 Quick Links


⚡ Tech Stack

  • React 19
  • Vite
  • Firebase 12
  • Redux Toolkit
  • React Router
Clone this wiki locally