2.3.1 Firebase Baas
This skill defines the architectural patterns for leveraging Firebase as a complete Backend-as-a-Service across all projects, with emphasis on cost efficiency for indie/bootstrapped applications.
1. Firebase Authentication
Goal: Frictionless, secure user identity management.
- Anonymous Auth: Always implement
signInAnonymously() as the default on first launch. This enables immediate usage without barriers while creating a persistent UID for data association.
- Account Linking: When the user is ready to commit (after value delivery), use
linkWithCredential() to upgrade their anonymous account to Google OAuth, Apple Sign-In, or Email/Password. All their existing data travels with them — zero data loss.
- Provider Priority: Google OAuth first (highest conversion on Android), Apple Sign-In (required by Apple for apps with third-party login), Email/Password as fallback.
- Security: Enable Email Enumeration Protection in Firebase Console. Set session duration appropriately. Implement multi-factor authentication (MFA) for admin/sensitive flows.
2. Firestore Data Modeling
Goal: Schema design optimized for read performance, cost, and real-time sync.
- Denormalization: Firestore is not a relational database. Duplicate data across documents to avoid joins. A user's display name should exist in every document that renders it — not fetched via a reference.
- Collection Structure: Use top-level collections for primary entities (
users, games, sessions). Use subcollections for owned data (users/{uid}/tickets, games/{gameId}/players).
- Document Size: Keep documents under 20KB for fast reads and real-time sync efficiency. Move large blobs (images, audio) to Cloud Storage and store only the URL reference.
- Indexes: Create composite indexes proactively for any query combining
where() clauses on different fields with orderBy(). Monitor the Firestore console for auto-suggested indexes.
- Reads Optimization: Use
getDoc() for one-time reads, onSnapshot() only when real-time updates are needed. Implement pagination with startAfter() and limit() to cap reads.
3. Firestore Security Rules
Goal: Zero-trust security enforced at the database level.
- Default Deny: Start every ruleset with
allow read, write: if false; and open access incrementally.
- Authentication Check: Every rule must verify
request.auth != null before granting any access.
- Ownership Enforcement: Users can only read/write their own documents:
allow read, write: if request.auth.uid == resource.data.userId;
- Data Validation: Use
request.resource.data to validate incoming writes: check field types, string lengths, required fields, and value ranges.
- Rate Limiting: Combine rules with Cloud Functions for write-heavy operations. Rules alone cannot rate-limit, but they can reject obviously invalid payloads.
4. Cloud Functions
Goal: Server-side logic without managing infrastructure.
- Triggers: Use Firestore triggers (
onCreate, onUpdate, onDelete) for reactive backend logic (e.g., recalculating leaderboards on score write). Use HTTPS callable functions for client-initiated server actions.
- Cold Start Mitigation: Set
minInstances: 1 for latency-critical functions. Keep function packages lean — avoid importing the entire Firebase Admin SDK when you only need Firestore.
- Idempotency: All functions must be idempotent. Firestore triggers can fire multiple times. Use transaction-based writes and check for existing state before mutating.
- Environment Config: Store secrets in Secret Manager (not environment variables). Access via
defineSecret() in Firebase Functions v2.
5. Firebase Cloud Messaging (FCM)
Goal: Contextual, behavior-driven push notifications.
- Token Management: Request notification permission after user demonstrates engagement (never on first load). Store the FCM token in the user's Firestore document. Refresh and update on every app launch.
- Topic Subscriptions: Use topics for broadcast messages (e.g.,
topic: "game-updates"). Use individual tokens for personalized nudges.
- Payload Design: Use
data messages (not notification) for full control over display. Handle the message in the service worker's push event to show custom notifications with actions.
- Batch Sending: Use
sendEachForMulticast() for sending to multiple tokens. Handle messaging/registration-token-not-registered errors by cleaning stale tokens.
6. Firebase Hosting
Goal: Fast, secure hosting with CDN and SSL out of the box.
- Configuration: Set
public to dist. Add rewrites for SPA: { "source": "**", "destination": "/index.html" }.
- Headers: Set
Cache-Control headers for static assets (long cache for hashed filenames, short for index.html). Add security headers: X-Content-Type-Options: nosniff, X-Frame-Options: DENY.
- Preview Channels: Use
firebase hosting:channel:deploy <channel-name> for temporary preview URLs during development.
- Multi-Site: Use
firebase hosting:sites:create <site-name> for hosting multiple apps under one Firebase project.
7. Cost Optimization for Indie Projects
Goal: Stay within Firebase's free Spark plan as long as possible; optimize Blaze plan usage.
- Reads: Cache Firestore responses on the client (IndexedDB or in-memory). Use
onSnapshot() listeners sparingly — they count reads on every change. Batch reads with getAll().
- Writes: Batch Firestore writes with
writeBatch() (counts as one operation per document, but reduces round trips). Debounce client-side writes.
- Cloud Functions: Minimize invocations. Use client-side logic for non-sensitive computations. Set memory allocation to minimum needed (128MB or 256MB).
- Storage: Compress images before upload. Use Cloud Storage lifecycle rules to auto-delete temporary files.
- Budget Alerts: Set budget alerts in Google Cloud Console at $5, $10, $25 thresholds. Monitor usage weekly in Firebase Console → Usage and billing.
8. Firebase Studio Workspaces
Goal: Leverage cloud-based development environments for rapid prototyping.
- Access: Utilize the 30 workspaces available via Google Developer Program. Each workspace provides a full cloud IDE with AI assistance.
- Use Cases: Rapid prototyping of new app ideas, testing Firebase integrations in isolation, collaborative development sessions.
- Limitations: Workspaces are transient — commit and push code to GitHub before closing. Don't rely on workspace-local storage for persistent work.
1---2name: firebase-baas3description: Firebase ecosystem patterns including Auth, Firestore data modeling, Cloud Functions, FCM, Hosting, Security Rules, Firebase Studio workspaces, and cost optimization for indie projects.4---56# 2.3.1 Firebase Baas78This skill defines the architectural patterns for leveraging Firebase as a complete Backend-as-a-Service across all projects, with emphasis on cost efficiency for indie/bootstrapped applications.910## 1. Firebase Authentication11**Goal:** Frictionless, secure user identity management.12* **Anonymous Auth:** Always implement `signInAnonymously()` as the default on first launch. This enables immediate usage without barriers while creating a persistent UID for data association.13* **Account Linking:** When the user is ready to commit (after value delivery), use `linkWithCredential()` to upgrade their anonymous account to Google OAuth, Apple Sign-In, or Email/Password. All their existing data travels with them — zero data loss.14* **Provider Priority:** Google OAuth first (highest conversion on Android), Apple Sign-In (required by Apple for apps with third-party login), Email/Password as fallback.15* **Security:** Enable Email Enumeration Protection in Firebase Console. Set session duration appropriately. Implement multi-factor authentication (MFA) for admin/sensitive flows.1617## 2. Firestore Data Modeling18**Goal:** Schema design optimized for read performance, cost, and real-time sync.19* **Denormalization:** Firestore is not a relational database. Duplicate data across documents to avoid joins. A user's display name should exist in every document that renders it — not fetched via a reference.20* **Collection Structure:** Use top-level collections for primary entities (`users`, `games`, `sessions`). Use subcollections for owned data (`users/{uid}/tickets`, `games/{gameId}/players`).21* **Document Size:** Keep documents under 20KB for fast reads and real-time sync efficiency. Move large blobs (images, audio) to Cloud Storage and store only the URL reference.22* **Indexes:** Create composite indexes proactively for any query combining `where()` clauses on different fields with `orderBy()`. Monitor the Firestore console for auto-suggested indexes.23* **Reads Optimization:** Use `getDoc()` for one-time reads, `onSnapshot()` only when real-time updates are needed. Implement pagination with `startAfter()` and `limit()` to cap reads.2425## 3. Firestore Security Rules26**Goal:** Zero-trust security enforced at the database level.27* **Default Deny:** Start every ruleset with `allow read, write: if false;` and open access incrementally.28* **Authentication Check:** Every rule must verify `request.auth != null` before granting any access.29* **Ownership Enforcement:** Users can only read/write their own documents: `allow read, write: if request.auth.uid == resource.data.userId;`30* **Data Validation:** Use `request.resource.data` to validate incoming writes: check field types, string lengths, required fields, and value ranges.31* **Rate Limiting:** Combine rules with Cloud Functions for write-heavy operations. Rules alone cannot rate-limit, but they can reject obviously invalid payloads.3233## 4. Cloud Functions34**Goal:** Server-side logic without managing infrastructure.35* **Triggers:** Use Firestore triggers (`onCreate`, `onUpdate`, `onDelete`) for reactive backend logic (e.g., recalculating leaderboards on score write). Use HTTPS callable functions for client-initiated server actions.36* **Cold Start Mitigation:** Set `minInstances: 1` for latency-critical functions. Keep function packages lean — avoid importing the entire Firebase Admin SDK when you only need Firestore.37* **Idempotency:** All functions must be idempotent. Firestore triggers can fire multiple times. Use transaction-based writes and check for existing state before mutating.38* **Environment Config:** Store secrets in Secret Manager (not environment variables). Access via `defineSecret()` in Firebase Functions v2.3940## 5. Firebase Cloud Messaging (FCM)41**Goal:** Contextual, behavior-driven push notifications.42* **Token Management:** Request notification permission after user demonstrates engagement (never on first load). Store the FCM token in the user's Firestore document. Refresh and update on every app launch.43* **Topic Subscriptions:** Use topics for broadcast messages (e.g., `topic: "game-updates"`). Use individual tokens for personalized nudges.44* **Payload Design:** Use `data` messages (not `notification`) for full control over display. Handle the message in the service worker's `push` event to show custom notifications with actions.45* **Batch Sending:** Use `sendEachForMulticast()` for sending to multiple tokens. Handle `messaging/registration-token-not-registered` errors by cleaning stale tokens.4647## 6. Firebase Hosting48**Goal:** Fast, secure hosting with CDN and SSL out of the box.49* **Configuration:** Set `public` to `dist`. Add rewrites for SPA: `{ "source": "**", "destination": "/index.html" }`.50* **Headers:** Set `Cache-Control` headers for static assets (long cache for hashed filenames, short for `index.html`). Add security headers: `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`.51* **Preview Channels:** Use `firebase hosting:channel:deploy <channel-name>` for temporary preview URLs during development.52* **Multi-Site:** Use `firebase hosting:sites:create <site-name>` for hosting multiple apps under one Firebase project.5354## 7. Cost Optimization for Indie Projects55**Goal:** Stay within Firebase's free Spark plan as long as possible; optimize Blaze plan usage.56* **Reads:** Cache Firestore responses on the client (IndexedDB or in-memory). Use `onSnapshot()` listeners sparingly — they count reads on every change. Batch reads with `getAll()`.57* **Writes:** Batch Firestore writes with `writeBatch()` (counts as one operation per document, but reduces round trips). Debounce client-side writes.58* **Cloud Functions:** Minimize invocations. Use client-side logic for non-sensitive computations. Set memory allocation to minimum needed (128MB or 256MB).59* **Storage:** Compress images before upload. Use Cloud Storage lifecycle rules to auto-delete temporary files.60* **Budget Alerts:** Set budget alerts in Google Cloud Console at $5, $10, $25 thresholds. Monitor usage weekly in Firebase Console → Usage and billing.6162## 8. Firebase Studio Workspaces63**Goal:** Leverage cloud-based development environments for rapid prototyping.64* **Access:** Utilize the 30 workspaces available via Google Developer Program. Each workspace provides a full cloud IDE with AI assistance.65* **Use Cases:** Rapid prototyping of new app ideas, testing Firebase integrations in isolation, collaborative development sessions.66* **Limitations:** Workspaces are transient — commit and push code to GitHub before closing. Don't rely on workspace-local storage for persistent work.