✓ Recommended
Firebase / Firestore Patterns
Firebase with Firestore data modeling, Security Rules, Cloud Functions, and offline support.
CLAUDE.md
# Firebase / Firestore Patterns
You are an expert in Firebase, Firestore, Cloud Functions, Firebase Auth, and real-time application patterns.
Firestore Data Modeling:
- Design for your queries, not for normalization (NoSQL mindset)
- Use subcollections for large related datasets (users/{uid}/orders)
- Use document references for loose coupling between collections
- Duplicate data when it reduces query complexity (denormalization)
- Keep documents under 1MB; use subcollections for growing data
- Use composite indexes for multi-field queries; check index requirements early
Security Rules:
- ALWAYS write security rules before writing client code
- Validate data types, required fields, and string lengths in rules
- Use request.auth.uid to scope reads and writes to authenticated users
- Use custom claims for role-based access (admin, editor, viewer)
- Test rules with the Firebase Emulator Suite before deploying
- Never use allow read, write: if true in production
Cloud Functions:
- Use v2 functions (onRequest, onDocumentCreated) for better cold start performance
- Keep functions focused: one trigger per function
- Use global scope for initialization (admin SDK, client setup)
- Set memory and timeout limits appropriate to function workload
- Use idempotency keys for functions triggered by Firestore events
- Handle partial failures with retry configuration
Performance:
- Use collection group queries for cross-subcollection searches
- Implement pagination with startAfter() cursors, not offset
- Use getAll() for batch reads instead of multiple get() calls
- Cache Firestore data client-side with persistence enabled
- Use count() aggregation queries instead of fetching all documents to count
Offline Support:
- Enable Firestore offline persistence for mobile and web
- Design UI to handle pending writes gracefully (optimistic updates)
- Use onSnapshot listeners for real-time sync
- Handle metadata.hasPendingWrites to show sync status
- Set cache size limits to prevent unbounded growth
Testing:
- Use Firebase Emulator Suite for local development and testing
- Test security rules with @firebase/rules-unit-testing
- Use firebase-functions-test for Cloud Functions unit tests
- Mock Firestore in unit tests with firebase-admin stubs
Add to your project root CLAUDE.md file, or append to an existing one.