Skip to content

Firebase Configuration

ThanuMahee12 edited this page Oct 19, 2025 · 1 revision

Firebase Configuration

Complete guide to configuring Firebase services for your application.

Authentication

Enable Email/Password Auth

  1. Firebase Console → Authentication
  2. Sign-in method → Email/Password
  3. Enable and Save

Enable Google Sign-In

  1. Sign-in method → Google
  2. Enable
  3. Select support email
  4. Save

Authentication in Code

import { signInWithEmailAndPassword, createUserWithEmailAndPassword } from 'firebase/auth'
import { auth } from './firebase/config'

// Sign up
const signUp = async (email, password) => {
  const userCredential = await createUserWithEmailAndPassword(auth, email, password)
  return userCredential.user
}

// Sign in
const signIn = async (email, password) => {
  const userCredential = await signInWithEmailAndPassword(auth, email, password)
  return userCredential.user
}

Firestore Database

Security Rules

Edit firestore.rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    
    // Users can read/write their own data
    match /users/{userId} {
      allow read: if request.auth != null;
      allow write: if request.auth.uid == userId;
    }
    
    // Public read, auth write
    match /posts/{postId} {
      allow read: if true;
      allow create: if request.auth != null;
      allow update, delete: if request.auth.uid == resource.data.userId;
    }
  }
}

Deploy Rules

firebase deploy --only firestore:rules

Firestore in Code

import { collection, addDoc, getDocs, query, where } from 'firebase/firestore'
import { db } from './firebase/config'

// Add document
const addUser = async (userId, data) => {
  await addDoc(collection(db, 'users'), {
    userId,
    ...data,
    createdAt: new Date()
  })
}

// Get documents
const getUsers = async () => {
  const snapshot = await getDocs(collection(db, 'users'))
  return snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }))
}

// Query documents
const getUserPosts = async (userId) => {
  const q = query(collection(db, 'posts'), where('userId', '==', userId))
  const snapshot = await getDocs(q)
  return snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }))
}

Firebase Storage

Security Rules

Edit storage.rules:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    
    // User-specific files
    match /users/{userId}/{allPaths=**} {
      allow read: if request.auth != null;
      allow write: if request.auth.uid == userId
                   && request.resource.size < 5 * 1024 * 1024; // 5MB limit
    }
    
    // Profile pictures
    match /profile-pictures/{userId} {
      allow read: if true;
      allow write: if request.auth.uid == userId
                   && request.resource.contentType.matches('image/.*')
                   && request.resource.size < 2 * 1024 * 1024; // 2MB limit
    }
  }
}

Deploy Rules

firebase deploy --only storage:rules

Storage in Code

import { ref, uploadBytes, getDownloadURL } from 'firebase/storage'
import { storage } from './firebase/config'

// Upload file
const uploadProfilePicture = async (userId, file) => {
  const storageRef = ref(storage, `profile-pictures/${userId}`)
  await uploadBytes(storageRef, file)
  const url = await getDownloadURL(storageRef)
  return url
}

Environment Variables

Required Variables

VITE_FIREBASE_API_KEY=AIza...
VITE_FIREBASE_AUTH_DOMAIN=your-app.firebaseapp.com
VITE_FIREBASE_PROJECT_ID=your-app-12345
VITE_FIREBASE_STORAGE_BUCKET=your-app-12345.appspot.com
VITE_FIREBASE_MESSAGING_SENDER_ID=123456789
VITE_FIREBASE_APP_ID=1:123456789:web:abcdef

Using Environment Variables

const firebaseConfig = {
  apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
  authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
  projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
  storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID,
  appId: import.meta.env.VITE_FIREBASE_APP_ID
}

Firebase Hosting

Configuration

firebase.json:

{
  "hosting": {
    "public": "dist",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

Deploy

npm run build
firebase deploy --only hosting

Best Practices

Security

  • ✅ Never commit .env files
  • ✅ Use strict security rules
  • ✅ Test rules in Firebase Console
  • ✅ Enable App Check for production

Performance

  • ✅ Use indexes for queries
  • ✅ Limit query results
  • ✅ Cache frequently accessed data
  • ✅ Optimize images before upload

Cost Management

  • ✅ Monitor usage in Firebase Console
  • ✅ Set up budget alerts
  • ✅ Use Firebase emulators for testing
  • ✅ Delete unused data regularly

Next: Development Workflow

📖 Documentation

Getting Started

Configuration

Advanced Topics

Deployment


🔗 Quick Links


⚡ Tech Stack

  • React 19
  • Vite
  • Firebase 12
  • Redux Toolkit
  • React Router

Clone this wiki locally