Books/Firebase Essentials/Firebase Cheat Sheet for AI Prompting

    Firebase Cheat Sheet for AI Prompting

    Firebase Cheat Sheet for AI Prompting

    Your complete reference for Firebase — CLI commands, Firestore operations, and AI prompts organized by what you're building. Bookmark this page!

    Firebase CLI Commands

    CommandWhat It Does
    firebase loginAuthenticate with Google
    firebase initSet up Firebase in your project
    firebase projects:listList your Firebase projects
    firebase use project-idSwitch active project
    firebase deployDeploy everything
    firebase deploy --only hostingDeploy only hosting
    firebase deploy --only firestore:rulesDeploy only Firestore rules
    firebase deploy --only functionsDeploy only Cloud Functions
    firebase deploy --only storageDeploy only Storage rules
    firebase emulators:startStart local emulators
    firebase hosting:channel:deploy previewCreate preview deployment
    firebase serveServe hosting locally

    Firestore Operations — Client SDK

    import {
      collection, doc, addDoc, setDoc, getDoc, getDocs,
      updateDoc, deleteDoc, query, where, orderBy, limit,
      onSnapshot, Timestamp
    } from "firebase/firestore";
    OperationCode
    Add (auto ID)addDoc(collection(db, "items"), data)
    Set (custom ID)setDoc(doc(db, "items", "id"), data)
    Get onegetDoc(doc(db, "items", "id"))
    Get allgetDocs(collection(db, "items"))
    QuerygetDocs(query(collection(db, "items"), where("field", "==", value)))
    UpdateupdateDoc(doc(db, "items", "id"), { field: value })
    DeletedeleteDoc(doc(db, "items", "id"))
    ListenonSnapshot(doc(db, "items", "id"), callback)

    Firestore Operations — Admin SDK

    import { getFirestore, Timestamp } from "firebase-admin/firestore";
    const db = getFirestore();
    OperationCode
    Adddb.collection("items").add(data)
    Setdb.collection("items").doc("id").set(data)
    Get onedb.collection("items").doc("id").get()
    Get alldb.collection("items").get()
    Querydb.collection("items").where("field", "==", value).get()
    Updatedb.collection("items").doc("id").update({ field: value })
    Deletedb.collection("items").doc("id").delete()

    Query Operators

    OperatorExampleMeaning
    ==where("status", "==", "active")Equals
    !=where("status", "!=", "deleted")Not equals
    <where("price", "<", 100)Less than
    <=where("price", "<=", 100)Less than or equal
    >where("age", ">", 18)Greater than
    >=where("age", ">=", 18)Greater than or equal
    inwhere("status", "in", ["active", "pending"])Matches any value in list
    array-containswhere("tags", "array-contains", "featured")Array has value
    orderByorderBy("createdAt", "desc")Sort results
    limitlimit(10)Limit number of results

    Authentication Quick Reference

    import { getAuth, signInWithPopup, signOut, onAuthStateChanged,
             GoogleAuthProvider, createUserWithEmailAndPassword,
             signInWithEmailAndPassword } from "firebase/auth";
    OperationCode
    Google sign-insignInWithPopup(auth, new GoogleAuthProvider())
    Email sign-upcreateUserWithEmailAndPassword(auth, email, password)
    Email sign-insignInWithEmailAndPassword(auth, email, password)
    Sign outsignOut(auth)
    Listen to authonAuthStateChanged(auth, (user) => {})
    Current userauth.currentUser

    Storage Quick Reference

    import { ref, uploadBytes, uploadBytesResumable,
             getDownloadURL, deleteObject, listAll } from "firebase/storage";
    OperationCode
    UploaduploadBytes(ref(storage, path), file)
    Upload with progressuploadBytesResumable(ref(storage, path), file)
    Get URLgetDownloadURL(ref(storage, path))
    DeletedeleteObject(ref(storage, path))
    List fileslistAll(ref(storage, folderPath))

    Cloud Functions Quick Reference

    // HTTP function
    import { onRequest } from "firebase-functions/v2/https";
    export const api = onRequest((req, res) => { res.json({ ok: true }); });
    
    // Callable function
    import { onCall } from "firebase-functions/v2/https";
    export const doSomething = onCall(async (request) => { return { result: "done" }; });
    
    // Firestore trigger
    import { onDocumentCreated } from "firebase-functions/v2/firestore";
    export const onNew = onDocumentCreated("items/{id}", (event) => { });
    
    // Scheduled function
    import { onSchedule } from "firebase-functions/v2/scheduler";
    export const daily = onSchedule("every day 00:00", async () => { });

    AI Prompts by Category

    Project Setup

    • "Set up a new React + TypeScript project with Firebase. Include Firestore, Authentication, and Hosting. Set up environment variables."
    • "I have a Firebase project called [name]. Help me initialize Firebase in my existing React app."
    • "Create the Firebase config file, service files, and auth context for my React app."
    • "Set up Firebase emulators for local development. I want to test Firestore, Auth, and Functions locally."

    Database Design

    • "I'm building a [type of app]. Design my Firestore database structure — what collections do I need and what fields should each document have?"
    • "I have these features: [list features]. What Firestore collections, documents, and relationships do I need?"
    • "Review my Firestore data structure and suggest improvements: [describe current structure]."
    • "Should I use subcollections or top-level collections for [this data]? What are the trade-offs?"

    Firestore CRUD

    • "Create a TypeScript service file for my [collection] with all CRUD operations, proper types, and timestamps."
    • "Write a Firestore query that gets all [items] where [condition], ordered by [field], limited to [number]."
    • "Add real-time listeners to my [component] so it updates automatically when Firestore data changes."
    • "Create a paginated query for my [collection]. Load 10 items at a time with a 'load more' button."
    • "Write a batch operation that updates [field] for all documents in [collection] where [condition]."

    Authentication

    • "Add Firebase Authentication to my app with Google sign-in and email/password. Include auth context and protected routes."
    • "Create a login page with email/password form, Google sign-in button, and a link to the signup page."
    • "Add role-based access control. Store user roles in Firestore and check them before showing admin pages."
    • "Implement password reset functionality with a 'Forgot Password' flow."

    Security Rules

    • "Write Firestore security rules for my app. Here's who can access what: [describe access patterns]."
    • "My app has these collections: [list them]. Write security rules that: [describe requirements]."
    • "I need rules where users can read all posts but only edit their own. Admins can edit everything."
    • "Write Storage security rules that limit uploads to 5MB and only allow image files."

    Hosting & Deployment

    • "Configure Firebase Hosting for my Vite/React app. Include rewrites for single-page routing and caching headers."
    • "Set up a deploy script in package.json that builds and deploys to Firebase Hosting."
    • "Help me connect my custom domain [domain.com] to Firebase Hosting."
    • "Set up preview deployments so I can test changes before going live."

    Cloud Functions

    • "Create a Cloud Function that sends a welcome email when a new user signs up."
    • "Write an HTTP Cloud Function that acts as an API endpoint for [purpose]."
    • "Create a scheduled function that runs every night and [does something]."
    • "Write a Firestore trigger that [does something] when a document in [collection] is created/updated/deleted."
    • "Create a callable function that [does something]. Include authentication checks."

    Cloud Storage

    • "Build a file upload component with Firebase Storage. Include drag-and-drop, progress bar, and file preview."
    • "Create a profile picture upload feature. Store the image in Storage and save the URL in the user's Firestore document."
    • "Build an image gallery that uploads to Firebase Storage and displays all images from a folder."
    • "Create a Cloud Function that generates a thumbnail when an image is uploaded to Storage."

    Full App Prompts

    • "Build a blog app with Firebase. Users can sign up, create posts with images, and comment on posts. Include an admin dashboard."
    • "Create a to-do app with Firebase. Features: user auth, CRUD tasks, categories, due dates, and real-time sync."
    • "Build a chat application with Firebase. Features: user auth, real-time messages, typing indicators, and chat rooms."
    • "Create an e-commerce product catalog with Firebase. Features: product listings, categories, search, image upload, and an admin panel to manage products."

    Debugging

    • "I'm getting this Firebase error: [paste error]. What does it mean and how do I fix it?"
    • "My Firestore query isn't returning results. Here's my query: [paste code]. What might be wrong?"
    • "My security rules are blocking reads/writes. Here are my rules: [paste rules]. And here's the operation: [describe]. Help me fix the rules."
    • "Firebase deploy is failing with this error: [paste error]. How do I fix it?"
    • "My Cloud Function works locally but fails after deployment. Here's the error: [paste error]."
    • "Firestore says I need an index. How do I create composite indexes?"

    Common Patterns Reference

    Service File Template

    // src/services/[name]Service.ts
    import { db } from "@/lib/firebase";
    import { collection, doc, addDoc, getDoc, getDocs,
             updateDoc, deleteDoc, query, orderBy, Timestamp } from "firebase/firestore";
    
    const COLLECTION = "your-collection";
    
    interface Item {
      id: string;
      // ... your fields
      createdAt: Timestamp;
      updatedAt: Timestamp;
    }
    
    type ItemInput = Omit<Item, "id" | "createdAt" | "updatedAt">;
    
    export const getItems = async (): Promise<Item[]> => {
      const snap = await getDocs(query(collection(db, COLLECTION), orderBy("createdAt")));
      return snap.docs.map(d => ({ id: d.id, ...d.data() } as Item));
    };
    
    export const createItem = async (data: ItemInput): Promise<string> => {
      const ref = await addDoc(collection(db, COLLECTION), {
        ...data, createdAt: Timestamp.now(), updatedAt: Timestamp.now()
      });
      return ref.id;
    };
    
    export const updateItem = async (id: string, data: Partial<ItemInput>): Promise<void> => {
      await updateDoc(doc(db, COLLECTION, id), { ...data, updatedAt: Timestamp.now() });
    };
    
    export const deleteItem = async (id: string): Promise<void> => {
      await deleteDoc(doc(db, COLLECTION, id));
    };

    Security Rules Template

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        // Public readable, auth required to write
        match /posts/{postId} {
          allow read: if true;
          allow create: if request.auth != null;
          allow update, delete: if request.auth != null
            && resource.data.authorId == request.auth.uid;
        }
    
        // User's own data only
        match /users/{userId} {
          allow read, write: if request.auth != null
            && request.auth.uid == userId;
        }
    
        // Admin only
        match /admin/{document=**} {
          allow read, write: if request.auth != null
            && exists(/databases/$(database)/documents/admins/$(request.auth.uid));
        }
      }
    }
    

    The Complete Firebase Workflow

    1. CREATE a Firebase project at console.firebase.google.com
    2. ENABLE the services you need (Firestore, Auth, Storage)
    3. INITIALIZE Firebase in your project (firebase init)
    4. CONFIGURE environment variables
    5. BUILD service files for Firestore operations
    6. DEVELOP your app with Firebase SDK
    7. SECURE your data with Firestore and Storage rules
    8. TEST locally with emulators
    9. DEPLOY with firebase deploy
    10. MONITOR in the Firebase Console
    

    Keep Learning

    Firebase has even more to offer:

    • Firebase Extensions — Pre-built solutions (resize images, send emails, translate text)
    • Remote Config — Change app behavior without deploying
    • Analytics — Understand how users interact with your app
    • Performance Monitoring — Track app speed and bottlenecks
    • App Check — Protect your backend from abuse

    Remember: Firebase is designed to let you focus on building your app, not managing infrastructure. Combined with AI coding tools, you can build and deploy full-stack applications faster than ever.

    Happy building!


    🌐 www.genai-mentor.ai