Firebase (GCP) Pocket Book — Uplatz
50 deep-dive flashcards • Wide layout • Fewer scrolls • 20+ Interview Q&A • Readable JS/TS examples
1) What is Firebase?
Firebase is a Google‑backed platform for building web/mobile apps quickly: Auth, Firestore/Realtime DB, Storage, Cloud Functions, Hosting, Analytics, Remote Config, FCM, and more. It integrates tightly with Google Cloud.
npm i firebase # Web v9 modular SDK
npm i firebase-admin # Admin SDK (Node server)
2) Firebase vs Google Cloud
Firebase provides developer‑friendly SDKs, hosted services, and managed security rules; Google Cloud offers granular primitives (Cloud Run, Pub/Sub, IAM). You can mix: e.g., Firebase Auth + Cloud Run API + Firestore.
# Link Firebase project to GCP billing & BigQuery export
3) Projects & Environments
Create separate Firebase projects per environment (dev/stage/prod). Use projectId aliases and per‑env config files.
firebase use --add # add dev/stage/prod aliases
firebase use prod
4) Web SDK v9 (Modular)
Initialize the app and use tree‑shakable imports.
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
const app = initializeApp({ apiKey: '…', authDomain: '…', projectId: '…' })
const auth = getAuth(app)
5) CLI & Emulator Suite
Use firebase-tools for deploys and local development with emulators for Auth, Firestore, Functions, Storage, Hosting.
npm i -g firebase-tools
firebase init
firebase emulators:start
6) Authentication Overview
Supports email/password, phone, OAuth providers (Google/GitHub), SAML/OIDC, anonymous. Secure client SDKs plus Admin SDK for server tasks.
import { signInWithEmailAndPassword } from 'firebase/auth'
7) Firestore vs Realtime DB
Firestore is document/collection, strong consistency, compound queries, scalable; Realtime DB is JSON tree, low‑latency realtime sync, simpler queries. Choose by data shape and latency needs.
# Firestore collections/docs vs RTDB paths
8) Storage
Firebase Storage uses Google Cloud Storage under the hood; store files with resumable uploads and security rules.
import { getStorage, ref, uploadBytes } from 'firebase/storage'
9) Cloud Functions (Gen 2)
Serverless functions on Google’s infra. Gen2 uses Cloud Run/Events; supports concurrency and regional control.
npm i -D firebase-functions firebase-admin
10) Q&A — “When should I pick Firebase?”
Answer: When you want rapid delivery with managed auth/data/storage, strong client SDKs, and realtime features. If you need bespoke VPCs, custom runtimes, or heavy CPU, mix with Cloud Run/GKE.
11) Auth Providers
Enable providers in Console and use modular APIs on the client.
import { GoogleAuthProvider, signInWithPopup } from 'firebase/auth'
const provider = new GoogleAuthProvider()
await signInWithPopup(auth, provider)
12) Auth State & Persistence
Listen for user changes and set persistence (local, session, none).
import { onAuthStateChanged, setPersistence, browserLocalPersistence } from 'firebase/auth'
await setPersistence(auth, browserLocalPersistence)
onAuthStateChanged(auth, (u) => console.log(u?.uid))
13) Custom Claims & Roles
Use Admin SDK to set custom claims for RBAC; read them on the client and enforce via rules.
// Node server (Admin)
import admin from 'firebase-admin'
admin.initializeApp()
await admin.auth().setCustomUserClaims(uid, { role: 'admin' })
14) Firestore Data Model
Organize data as collections of documents with subcollections; avoid unbounded arrays and large docs.
import { getFirestore, collection, addDoc } from 'firebase/firestore'
const db = getFirestore(app)
await addDoc(collection(db, 'users'), { email, createdAt: Date.now() })
15) Queries & Indexes
Compound queries require composite indexes; use limits and cursors for pagination.
import { query, where, orderBy, limit, getDocs } from 'firebase/firestore'
const q = query(collection(db,'orders'), where('status','==','paid'), orderBy('createdAt','desc'), limit(20))
const snap = await getDocs(q)
16) Transactions & Batched Writes
Keep transactions small; batched writes allow atomic multi‑doc updates.
import { writeBatch, doc } from 'firebase/firestore'
const batch = writeBatch(db)
batch.update(doc(db,'users',uid), { plan:'pro' })
batch.set(doc(db,'logs',id), { type:'upgrade' })
await batch.commit()
17) Firestore Security Rules (Basics)
Rules gate read/write based on auth and document data; test with the emulator.
rules_version = '2';
service cloud.firestore { match /databases/{db}/documents {
match /users/{uid} {
allow read: if request.auth != null && request.auth.uid == uid;
allow write: if false; // write via Cloud Functions only
}
} }
18) Realtime Database Basics
Low‑latency JSON tree; great for presence/chat. Structure with shallow paths and fan‑out writes.
import { getDatabase, ref, onValue } from 'firebase/database'
const rtdb = getDatabase(app)
onValue(ref(rtdb,'presence/'+uid), (snap) => console.log(snap.val()))
19) Offline & Caching
Firestore SDK supports offline persistence (web/mobile). Handle merge conflicts on reconnect.
import { enableIndexedDbPersistence } from 'firebase/firestore'
try { await enableIndexedDbPersistence(db) } catch(e){ /* tabs? */ }
20) Q&A — “How to control Firestore costs?”
Answer: Denormalize for fewer reads, use selective queries and limits, cache on the client, stream with listeners only when needed, and batch writes. Prefer Cloud Functions for server‑side aggregation.
21) Cloud Functions Triggers
HTTP, callable, Firestore/RTDB triggers, Storage, Auth, Pub/Sub, and scheduled functions.
// functions/src/index.ts
import * as functions from 'firebase-functions/v2'
import * as logger from 'firebase-functions/logger'
export const hello = functions.https.onRequest((req, res) => {
logger.info('hello'); res.json({ ok:true })
})
22) Gen 2 Options
Choose region, memory, concurrency, min instances to reduce cold starts.
export const api = functions.https.onRequest({ region:'asia-south1', memory:'512MiB', minInstances:1, concurrency:80 }, handler)
23) Callable vs HTTP
Callable simplifies auth & client errors; HTTP is flexible for external clients.
export const addNote = functions.https.onCall(async (data, ctx) => {
if(!ctx.auth) throw new functions.https.HttpsError('unauthenticated','login')
return { id: await createNote(ctx.auth.uid, data) }
})
24) Pub/Sub & Schedules
Schedule CRON‑like tasks or process topics.
export const nightly = functions.scheduler.onSchedule('0 18 * * *', () => cleanup())
25) Storage Uploads & Rules
Validate file types, sizes, and paths via Storage rules; generate signed URLs in Admin code.
import { getStorage, ref, uploadBytes } from 'firebase/storage'
const storage = getStorage(app)
await uploadBytes(ref(storage, `avatars/${uid}.jpg`), file)
26) Firebase Cloud Messaging (FCM)
Send push notifications to devices/topics; use the Admin SDK from servers.
await admin.messaging().send({ token, notification:{ title:'Hi', body:'Welcome!' } })
27) Hosting Basics
Global CDN, automatic SSL, SPA rewrites. Use firebase.json for config.
{
"hosting": { "public": "dist", "ignore": ["**/.*"], "rewrites": [{"source":"**","destination":"/index.html"}] }
}
28) SSR with Hosting + Functions/Run
Use Hosting rewrites to an SSR endpoint in Functions or Cloud Run.
{
"hosting": { "rewrites": [{ "source": "**", "function": "ssr" }] }
}
29) App Check
Protect resources from abuse by attesting app integrity (DeviceCheck/Play Integrity/recaptcha‑v3). Enforce on Firestore/Storage/Functions.
import { initializeAppCheck, ReCaptchaV3Provider } from 'firebase/app-check'
initializeAppCheck(app, { provider: new ReCaptchaV3Provider('site-key'), isTokenAutoRefreshEnabled: true })
30) Q&A — “Reduce cold starts?”
Answer: Use Gen2 with minInstances > 0, regional proximity (e.g., asia-south1 for India), smaller bundles, and keep dependencies lean.
31) Analytics & BigQuery
Enable Google Analytics for Firebase to track events; export raw events to BigQuery for analysis/ML.
# Query GA4 export tables in BigQuery for funnels/retention
32) Remote Config
Feature flags and parameterization with conditions (country, app version, user property).
import { getRemoteConfig, fetchAndActivate, getValue } from 'firebase/remote-config'
const rc = getRemoteConfig(app)
await fetchAndActivate(rc)
const isNewUI = getValue(rc,'new_ui').asBoolean()
33) A/B Testing
Combine Remote Config with A/B Testing to evaluate variants on metrics like retention, revenue, or conversions.
# Configure experiments in the console; read params via Remote Config
34) Performance Monitoring
Track app start, HTTP latency, and custom traces; investigate slow endpoints.
// web perf monitoring SDK (when applicable)
35) Emulator Suite
Develop offline with local Auth/Firestore/Functions/Storage; seed data and run tests.
export FIREBASE_EMULATORS_HOST=localhost:4000
36) Testing Security Rules
Use the rules unit testing library with the emulator to verify allow/deny scenarios.
import { initializeTestEnvironment } from '@firebase/rules-unit-testing'
37) Unit Test Functions
Mock context and assert responses; prefer small, pure modules.
// jest.config.js & firebase-functions-test for v1; for v2 test handler modules
38) CI/CD with GitHub Actions
Automate deploys with environment targets and preview channels.
- uses: FirebaseExtended/action-hosting-deploy@v0
with: { channelId: 'preview', projectId: 'your-app' }
39) Multiple Projects & Tenants
Support multiple Firebase projects in one codebase using environment files and initializeApp per tenant.
const appA = initializeApp(cfgA, 'A')
const appB = initializeApp(cfgB, 'B')
40) Q&A — “Migrate beyond Firebase?”
Answer: Keep IDs stable, export Firestore to GCS, mirror traffic, then cut over to Cloud Run/Bigtable/Spanner as needed. Use Pub/Sub for dual‑write during transition.
41) Pricing & Quotas
Firestore charges per document read/write/storage; Functions per GB‑s & invocations; Storage per GB/month & egress; FCM free. Monitor usage and set budgets/alerts in Cloud Billing.
# Use Cost Table + Budgets & Alerts in GCP console
42) Monitoring & Logs
Use Cloud Logging/Monitoring dashboards; add structured logs in Functions and trace IDs.
import * as logger from 'firebase-functions/logger'
logger.info('event', { user: uid })
43) Secrets Management
Store secrets in Google Secret Manager; access via Functions runtime and do not commit to repo.
export const api = functions.https.onRequest({ secrets: ['STRIPE_KEY'] }, (req,res) => {...})
44) Backups & Exports
Export Firestore collections to GCS; schedule periodic exports.
gcloud firestore export gs://my-bucket/backup_$(date +%F)
45) Privacy & Compliance
Use user deletion APIs, data retention policies, and regional resources; document processing of PII and obtain consent where required.
await admin.auth().deleteUser(uid)
46) Firebase Extensions
Prebuilt functions for tasks like image resize, full‑text search (with Algolia), payments. Review quotas and costs.
# Install via Console or CLI; configure parameters per env
47) Common Pitfalls
Over‑listening to collections, unbounded queries, writing from the client without rules, storing secrets in client code, and ignoring indexes.
# Prefer server-side privileged operations via Admin SDK
48) Production Checklist
- Per‑env Firebase projects & configs
- Security rules with unit tests & emulator
- Indexing strategy & pagination
- Budgets/alerts, logs & metrics
- Functions gen2 with regional settings
- Backups/exports and data governance
49) Example App Skeleton
Minimal web app + functions layout for clarity and CI friendliness.
/web
src/main.ts # init app/auth/firestore
/functions
src/index.ts # https routes, triggers
firebase.json
.firebaserc
50) Interview Q&A — 20 Practical Questions (Firebase‑focused)
1) Why Firebase for startups? Rapid prototyping, managed backend, strong client SDKs.
2) Firestore vs RTDB? Documents vs JSON tree; queries vs realtime simplicity.
3) How to secure writes? Security rules + callable/HTTP functions; avoid direct privileged writes from clients.
4) Control costs? Denormalize, indexes, limits, caching, server aggregation.
5) What is App Check? Attestation to reduce abuse; enforce on resources.
6) Callable vs HTTP? Callable simplifies auth/errors for trusted clients; HTTP for public/external.
7) Offline support? Firestore offline cache; careful with conflict resolution.
8) When to use Admin SDK? Server‑side privileged tasks (claims, batch ops, CRON).
9) How to handle files? Storage with rules; process via functions; generate signed URLs.
10) Multi‑region? Choose nearest region; understand replication & egress.
11) Backups? Firestore export to GCS; verify restores.
12) Auth providers tradeoffs? Simplicity vs friction (email/phone vs OAuth).
13) Index management? Define in firestore.indexes.json; deploy with CLI.
14) Testing rules? Emulator + rules unit tests.
15) What causes cold starts? Zero instances, large deps; mitigate with minInstances.
16) BigQuery export? For Analytics/Crashlytics; advanced reporting.
17) Rate limiting? Via rules validations, Functions middleware, or API gateways.
18) GDPR/PII? Data minimization, consent, deletion APIs, regionality.
19) Extensions? Prebuilt automations—evaluate cost and fit.
20) When not to use Firebase? Very complex transactional workloads, massive analytical queries—consider Cloud SQL/Spanner/BigQuery.