firebase-storage
Skill: firebase-storage
Version: 1.0.0 Purpose: Build with Firebase Cloud Storage — file uploads, downloads, and secure access Author: The Forge Last Updated: 2025-07-14
Title
Firebase Cloud Storage - Implement file uploads, downloads, and secure storage with Firebase Cloud Storage including signed URLs, security rules, image processing, and CDN optimization
File Structure
forge-plugin/skills/firebase-storage/
├── SKILL.md # This file - mandatory workflow
└── examples.md # Usage scenarios and examples
Required Reading
Before executing this skill, load context and memory via interfaces:
-
Context: Use
contextProvider.getDomainIndex("schema")for relevant domain context. See ContextProvider Interface. -
Skill memory: Use
memoryStore.getSkillMemory("firebase-storage", "{project-name}")for previous Storage configurations. See MemoryStore Interface.
Interface References
- Context: Loaded via ContextProvider Interface
- Memory: Accessed via MemoryStore Interface
- Shared Patterns: Shared Loading Patterns
- Schemas: Validated against context_metadata.schema.json and memory_entry.schema.json
Design Requirements
Core Functionality
This skill must:
- Implement file uploads (web, mobile, server — resumable, multipart, and simple)
- Generate download URLs (signed URLs, public URLs, download tokens)
- Write storage security rules (authentication, file type/size validation, path-based access)
- Manage file metadata (content type, custom metadata, cache control headers)
- Configure resumable uploads (progress tracking, pause/resume, retry on failure)
- Set up image resizing and thumbnails (Firebase Extensions, Cloud Functions triggers)
- Optimize CDN caching (cache control headers, CDN invalidation strategies)
- Configure CORS (cross-origin access for browser-based uploads/downloads)
- Organize storage buckets (path conventions, multi-bucket strategies, lifecycle rules)
- Monitor and manage quotas (bandwidth limits, storage limits, rate limiting)
Output Requirements
Generate complete, production-ready Cloud Storage implementations with:
- Upload implementations (Web, Admin, Mobile SDKs)
- Download URL generation with appropriate expiration
- Storage security rules (storage.rules)
- CORS configuration (cors.json)
- File metadata management code
- Image processing pipeline setup (resize, thumbnail, watermark)
- Bucket organization documentation
- Quota monitoring configuration
Quality Requirements
Generated implementations must:
- Follow Cloud Storage best practices (file size limits, naming conventions, folder structure)
- Include comprehensive security rules (never deploy with open rules)
- Handle edge cases (upload cancellation, network failures, concurrent access, oversized files)
- Be SDK-appropriate (Web v9 modular, Admin SDK, Flutter, iOS, Android)
- Include error handling (quota exceeded, permission denied, file not found, network timeout)
- Be well-documented (bucket structure, upload flows, security rule logic)
9 Common Storage Errors Prevented
This skill actively prevents these frequently encountered Cloud Storage mistakes:
1. Missing CORS Configuration
Error: No 'Access-Control-Allow-Origin' header is present on the requested resource
Prevention: Always generate a cors.json configuration and deploy it with gsutil cors set cors.json gs://bucket-name. Include allowed origins, methods (GET, POST, PUT, DELETE), and headers (Content-Type, Authorization).
2. Oversized File Uploads Without Client Validation
Error: Wasted bandwidth and failed uploads from files exceeding limits
Prevention: Always validate file size on the client before uploading. Enforce size limits in security rules with request.resource.size < maxSize. Implement chunked/resumable uploads for large files (>5 MB).
3. Insecure Storage Security Rules
Error: Data breach from allow read, write: if true;
Prevention: Never generate open rules. Always require authentication, validate file types via content type checks, enforce path-based ownership (request.auth.uid == userId), and restrict file sizes.
4. Expired or Invalid Download URLs
Error: 403 Forbidden or 401 Unauthorized when accessing signed URLs after expiration
Prevention: Set appropriate expiration times for signed URLs (default 1 hour, max 7 days). Implement URL refresh logic before expiration. Use long-lived download tokens for persistent public access instead of signed URLs.
5. Missing Content-Type Metadata
Error: Files served with application/octet-stream instead of correct MIME type, breaking browser rendering
Prevention: Always set contentType metadata during upload. Detect MIME type from file extension or file header. Validate content type in security rules with request.resource.contentType.matches('image/.*').
6. No Upload Progress or Resumable Handling
Error: Users see no feedback during uploads; large uploads fail without recovery
Prevention: Always implement upload progress callbacks with uploadTask.on('state_changed'). Use resumable uploads for files over 5 MB. Implement pause/resume/cancel controls. Handle storage/retry-limit-exceeded with user feedback.
7. Unorganized Bucket Structure
Error: Flat file dumping making files impossible to query, manage, or secure
Prevention: Design a hierarchical path structure (e.g., users/{uid}/profile/avatar.jpg). Use consistent naming conventions. Separate public and private content into distinct paths. Document the bucket organization.
8. Missing Cleanup for Deleted Resources
Error: Orphaned files consuming storage quota after parent resources are deleted Prevention: Implement Cloud Functions triggers to delete associated files when parent documents are removed. Use lifecycle rules for temporary files. Track file references in Firestore for cleanup verification.
9. CDN Cache Serving Stale Content
Error: Updated files not visible to users due to aggressive cache headers
Prevention: Use versioned file paths or unique filenames (e.g., avatar_v2.jpg or content-hash naming). Set appropriate Cache-Control headers. Use cacheControl: 'public, max-age=3600' for static assets and no-cache for frequently updated files.
Instructions
MANDATORY STEPS (Must Execute in Order)
Step 1: Initial Analysis
Purpose: Understand the Cloud Storage implementation requirements
Actions:
- Identify the application type (web, mobile, server-side)
- Determine the SDK environment (Web v9 modular, Admin SDK, Flutter, iOS, Android)
- Review existing Storage configuration if present (firebase.json, storage.rules, cors.json)
- Understand the file types and sizes to be stored (images, documents, videos, user-generated content)
- Identify access patterns (public vs private, shared access, temporary URLs)
- Note any existing bucket structure or migration needs
- Determine image processing requirements (thumbnails, resizing, format conversion)
Output: Clear understanding of Storage requirements and constraints
Step 2: Load Memory
Purpose: Retrieve previous Cloud Storage configurations for this project
Follow Standard Memory Loading with
skill="firebase-storage"anddomain="schema".
Actions:
- Use
memoryStore.getSkillMemory("firebase-storage", "{project-name}")to load project memory. See MemoryStore Interface. - If memory exists, review:
bucket_structure.md- Existing bucket organization and path conventionssecurity_rules.md- Current security rules and access patternsupload_patterns.md- Established upload flows and file handlingcdn_config.md- CDN caching and CORS configurationquota_management.md- Storage limits and monitoring setup
- If not exists, note this is first-time Storage setup
Output: Understanding of project Storage history or recognition of new project
Step 3: Load Context
Purpose: Load relevant storage and file management knowledge
Follow Standard Context Loading for the
schemadomain. Stay within the file budget declared in frontmatter.
Actions:
- Use
contextProvider.getDomainIndex("schema")for data storage context - Load relevant context files based on requirements:
- File storage patterns and best practices
- Security best practices
- CDN and caching optimization guidelines
- Note any best practices for Cloud Storage implementation
Output: Comprehensive understanding of Cloud Storage patterns and best practices
Step 4: Storage Implementation
Purpose: Design and implement the Cloud Storage solution
Actions:
A. Bucket Organization and Path Design:
-
Design path hierarchy:
- Map file types to path segments (e.g.,
users/{uid}/avatars/,posts/{postId}/media/) - Separate public and private content paths
- Define naming conventions (original filenames, UUIDs, content-hash)
- Plan for multi-bucket strategies if needed (hot/cold storage)
- Document path structure for team reference
- Map file types to path segments (e.g.,
-
File metadata strategy:
- Define custom metadata fields per file type
- Set content type detection and validation
- Configure cache control headers per path
- Plan content disposition for downloads vs inline viewing
B. Security Rules:
-
Design storage security rules (storage.rules):
- Authentication requirements per path
- File type validation (
request.resource.contentType) - File size limits (
request.resource.size) - Path-based ownership (
request.auth.uid == userId) - Role-based access using custom claims
- Rate limiting patterns
-
Security rules testing:
- Provide test scenarios for rules
- Cover allow and deny cases
- Test edge cases (wrong file type, oversized files, unauthenticated access)
C. Upload Implementation:
- Simple uploads: Small files (<5 MB) with
uploadBytes() - Resumable uploads: Large files with
uploadBytesResumable()and progress tracking - Server-side uploads: Admin SDK uploads with
bucket.upload() - Upload controls: Pause, resume, cancel functionality
- Progress tracking: Real-time upload percentage with
state_changedobserver - Client validation: File type, size, and dimension checks before upload
D. Download URL Generation:
- Signed URLs: Time-limited access with configurable expiration
- Download tokens: Long-lived public URLs via
getDownloadURL() - Public URLs: CDN-served public content
- URL refresh: Automatic re-generation before expiration
- Streaming downloads: Large file downloads with progress
E. Image Processing and Thumbnails:
- Resize on upload: Cloud Functions triggered by storage events
- Thumbnail generation: Multiple sizes (small, medium, large)
- Format conversion: WebP optimization for web delivery
- Watermarking: Overlay watermarks on uploaded images
- Firebase Extensions: Configure "Resize Images" extension
F. CORS and CDN Configuration:
- CORS configuration: Generate and deploy
cors.json - Cache headers: Set
Cache-Controlper file type - CDN invalidation: Strategies for updated content
- Custom domains: Configure custom CDN domains if needed
Output: Complete Cloud Storage implementation
Step 5: Generate Output
Purpose: Produce deliverable artifacts
Actions:
- Save output to
/claudedocs/firebase-storage_{project}_{YYYY-MM-DD}.md - Follow naming conventions in
../OUTPUT_CONVENTIONS.md - Generate deliverable files:
storage.rules- Security rulescors.json- CORS configuration- Bucket organization documentation
- Upload implementation code (appropriate SDK)
- Download URL generation code
- Image processing Cloud Functions (if applicable)
- Quota monitoring setup
- Include the 9-error prevention checklist in output
Output: Complete, production-ready Cloud Storage implementation artifacts
Step 6: Update Memory
Purpose: Store configuration for future reference
Follow Standard Memory Update for
skill="firebase-storage". Store any newly learned patterns, conventions, or project insights.
Actions:
- Use
memoryStore.update(layer="skill-specific", skill="firebase-storage", project="{project-name}", ...)to store: - bucket_structure.md:
- Path hierarchy and naming conventions
- File type to path mappings
- Multi-bucket strategies
- Public vs private path separation
- security_rules.md:
- Current storage security rules
- File type and size validation logic
- Access control patterns
- Rule testing results
- upload_patterns.md:
- Upload implementation details (simple, resumable, server-side)
- Client-side validation rules
- Progress tracking configuration
- File processing pipelines
- cdn_config.md:
- CORS configuration
- Cache control headers per path
- CDN invalidation strategies
- Custom domain setup
- quota_management.md:
- Storage quota limits
- Bandwidth monitoring
- Cleanup automation rules
- Cost optimization notes
Output: Memory stored for future skill invocations
Best Practices
Bucket Organization
- Use structured paths: Design paths around ownership and access patterns (e.g.,
users/{uid}/) - Separate public and private: Keep publicly accessible files in a distinct path
- Avoid deep nesting: Limit path depth to 3-4 levels for manageability
- Use consistent naming: Choose UUID or content-hash naming to avoid collisions
- Document your structure: Maintain a bucket map for the team
Security Rules
- Never deploy open rules: Always require authentication for writes
- Validate file types: Check
request.resource.contentTypeagainst allowed MIME types - Enforce size limits: Use
request.resource.sizeto prevent oversized uploads - Path-based ownership: Ensure users can only write to their own paths
- Keep rules simple: Complex rules are harder to audit and more error-prone
Upload Optimization
- Validate before upload: Check file type, size, and dimensions on the client
- Use resumable uploads: For any file over 5 MB
- Show progress: Always provide upload progress feedback to users
- Handle failures gracefully: Implement retry logic with exponential backoff
- Compress before upload: Resize images and compress files client-side when possible
CDN and Caching
- Set cache headers: Configure
Cache-Controlbased on content update frequency - Use versioned paths: Append version or hash to filenames for cache busting
- Configure CORS early: Set up CORS before any browser-based access
- Monitor bandwidth: Track CDN usage to avoid unexpected costs
- Use appropriate formats: Serve WebP for web, optimize image quality settings
Error Handling
Common Issues
- Permission denied: Check security rules and user authentication state
- CORS errors: Verify
cors.jsonis deployed and includes the requesting origin - File not found: Handle gracefully with fallback UI or placeholder images
- Quota exceeded: Implement storage monitoring and alert on thresholds
- Network errors: Use resumable uploads, implement retry logic
Debugging
- Use Firebase Emulator: Test uploads and rules locally without affecting production
- Check rules in console: Use the Storage Rules simulator for testing
- Monitor in Firebase Console: Track storage usage, bandwidth, and operations
- Enable debug logging: Check browser network tab for detailed error responses
- Review CORS config: Use
gsutil cors get gs://bucket-nameto verify deployed configuration
Compliance Checklist
Before completing, verify:
- All mandatory workflow steps executed in order
- Standard Memory Loading pattern followed (Step 2)
- Standard Context Loading pattern followed (Step 3)
- Output saved with standard naming convention
- Standard Memory Update pattern followed (Step 6)
- Security rules require authentication (no open rules)
- CORS configuration generated and documented
- File type and size validation implemented (client and rules)
- Upload progress tracking implemented for large files
- 9-error prevention checklist verified
Version History
| Version | Date | Changes |
|---|---|---|
| 1.0.0 | 2025-07-14 | Initial release with interface-based patterns, 9-error prevention, comprehensive Cloud Storage workflow |
Related Skills
- firebase-firestore: For managing Firestore documents that reference stored files
- database-schema-analysis: For analyzing data structures that include file references
- generate-azure-functions: For server-side file processing patterns