7. Cloud Storage: Files, Buckets & Access Control
Scalable File Storage with Firebase Cloud Storage
Firebase Cloud Storage is Google Cloud Storage with Firebase integration. It provides scalable file storage for images, videos, and other user-generated content. Files are stored in buckets and served via a global CDN. Access control is managed through Security Rules integrated with Firebase Authentication.
Cloud Storage is built on Google Cloud Storage, which provides enterprise-grade durability and availability. Files are automatically replicated across multiple regions. The CDN caches files at the edge for fast delivery. Security Rules control access to files. You can restrict access based on authentication, file path, and metadata. Cloud Storage integrates with Cloud Functions for server-side processing. Understanding Cloud Storage is essential for building applications with user-generated content. Always validate file uploads on the server side for security.
Uploading and Downloading Files
Uploading files to Cloud Storage is straightforward. You can upload from a file input, a Blob, or a string. The upload provides progress events for large files. You can specify metadata like content type and custom attributes. Downloads are similarly simple — you can download to a Blob, a file, or a data URL. Cloud Storage supports resumable uploads for large files. This means you can resume interrupted uploads without losing progress. Use the getDownloadURL() method to get a public URL for a file. For private files, use signed URLs or Security Rules. Understanding uploads and downloads is essential for building applications with file support.
import { getStorage, ref, uploadBytes, getDownloadURL, deleteObject } from 'firebase/storage'; const storage = getStorage(); // Upload a file const file = event.target.files[0]; const storageRef = ref(storage, `users/${userId}/${file.name}`); const snapshot = await uploadBytes(storageRef, file); // Get download URL const downloadURL = await getDownloadURL(storageRef); // Update user profile with avatar URL await updateDoc(doc(db, 'users', userId), { avatarURL: downloadURL }); // Delete a file await deleteObject(storageRef);
Storage Security Rules
Storage Security Rules control access to files in Cloud Storage. They work similarly to Firestore rules but apply to file paths. You can restrict access based on authentication, file path, and metadata. For example, you can allow users to upload files only to their own folder. Storage rules support path wildcards for flexible matching. You can validate file types, sizes, and content types using metadata. Rules are evaluated on every operation. Understanding Storage rules is essential for securing user-generated content. Always validate file types and sizes to prevent abuse. Use signed URLs for temporary access to private files.
service firebase.storage {
match /b/{bucket}/o {
// Users can only access files in their own folder
match /users/{userId}/{allPaths=**} {
allow read, write: if request.auth.uid == userId;
}
// Public files are readable by everyone
match /public/{allPaths=**} {
allow read: if true;
allow write: if request.auth != null;
}
// Validate file uploads
match /uploads/{userId}/{fileName} {
allow write: if request.auth.uid == userId &&
request.resource.size < 5 * 1024 * 1024 && // 5MB limit
(request.resource.contentType.matches('image/.*') ||
request.resource.contentType.matches('application/pdf'));
}
}
}
File Metadata and Processing
File metadata includes content type, size, custom attributes, and time of upload. You can set custom metadata when uploading files. This metadata is accessible in Security Rules. Cloud Functions can process uploaded files — for example, generating thumbnails for images. File processing is essential for user-generated content. You can use Cloud Functions to validate images, resize them, and extract metadata. Cloud Functions trigger on file upload events. This enables server-side processing without managing infrastructure. Use Cloud Functions for image optimization, video transcoding, and other processing tasks.
// Cloud Function to generate thumbnail on upload import * as functions from 'firebase-functions'; import * as admin from 'firebase-admin'; import * as sharp from 'sharp'; export const generateThumbnail = functions.storage.object() .onFinalize(async (object) => { const filePath = object.name; if (!filePath) return; // Only process images const contentType = object.contentType; if (!contentType || !contentType.startsWith('image/')) return; // Generate thumbnail const bucket = admin.storage().bucket(object.bucket); const file = bucket.file(filePath); const [buffer] = await file.download(); const thumbnailBuffer = await sharp(buffer) .resize(200, 200, { fit: 'cover' }) .toBuffer(); // Save thumbnail const thumbnailPath = `thumbnails/${filePath}`; const thumbnailFile = bucket.file(thumbnailPath); await thumbnailFile.save(thumbnailBuffer, { metadata: { contentType: 'image/jpeg' } }); });
Knowledge Check
Ready to test your understanding of 7. Cloud Storage: Files, Buckets & Access Control?