8. Cloud Functions: Serverless Backend Logic
Your Serverless Backend, Automatically Scaled
Firebase Cloud Functions are serverless Node.js functions that run in response to events. They handle webhooks, scheduled tasks, and complex backend logic without managing servers. Cloud Functions automatically scale with your application, and you pay only for what you use.
Cloud Functions run on Google Cloud Functions, providing enterprise-grade reliability and scalability. Cold starts are typically under 100ms. Functions can connect to Firestore, Realtime Database, Cloud Storage, and external APIs. They're the perfect place for logic that shouldn't run on the client — like processing payments, sending emails, or validating data. Understanding Cloud Functions is essential for building complete Firebase applications. They fill the gap between client-side code and back-end services. Use Cloud Functions for any logic that requires server-side execution.
The Cloud Functions Runtime
Cloud Functions use Node.js (v18+) with full access to the Firebase Admin SDK. The Admin SDK provides privileged access to all Firebase services, bypassing Security Rules. This means you can perform admin operations like setting user roles, deleting accounts, or aggregating data. Functions are triggered by events — Firestore writes, authentication events, HTTP requests, and Cloud Storage changes. Each function is isolated and runs in its own container. You can write functions in TypeScript or JavaScript. The Firebase CLI handles deployment and management. Understanding the runtime is essential for writing efficient Cloud Functions. Use environment variables for configuration. Implement error handling for reliability.
// Cloud Function triggered by Firestore document creation import * as functions from 'firebase-functions'; import * as admin from 'firebase-admin'; admin.initializeApp(); // Firestore trigger const onUserCreated = functions.firestore .document('users/{userId}') .onCreate(async (snap, context) => { const userData = snap.data(); const userId = context.params.userId; // Send welcome email await sendWelcomeEmail(userData.email, userData.name); // Create user profile await admin.firestore().collection('profiles').doc(userId).set({ userId: userId, createdAt: admin.firestore.FieldValue.serverTimestamp() }); }); // HTTP trigger const apiHandler = functions.https.onRequest(async (req, res) => { // Set CORS headers res.set('Access-Control-Allow-Origin', '*'); res.set('Access-Control-Allow-Methods', 'GET, POST'); if (req.method === 'OPTIONS') { res.status(204).send(''); return; } // Handle request const { action, data } = req.body; // ... business logic res.json({ success: true }); });
Deployment & Environment Variables
Deploying Cloud Functions is simple with the Firebase CLI. Functions are deployed to Google Cloud and automatically scaled. The CLI supports incremental builds — only changed functions are deployed. Environment variables allow configuration without hardcoding secrets. Use .env files for local development. The Firebase Console provides logs and monitoring for deployed functions. The emulator suite allows local testing without affecting production. Understanding deployment is essential for managing production environments. Use CI/CD pipelines for automated deployments. Monitor function performance and errors with Firebase Console.
# Install Firebase CLI npm install -g firebase-tools # Login firebase login # Initialize functions firebase init functions # Deploy all functions firebase deploy --only functions # Deploy specific function firebase deploy --only functions:onUserCreated # Set environment variables firebase functions:config:set stripe.secret_key="sk_live_..." # Run emulator for local testing firebase emulators:start
Real-World Patterns
Cloud Functions excel at several common patterns. Webhooks — receive Stripe/GitHub/Twilio webhooks, validate signatures, write to your database. Email on Sign-up — trigger a function on auth.user.create to send welcome emails. Image Processing — resize uploaded images on Cloud Storage trigger. Data Aggregation — compute statistics and update aggregate documents. Scheduled Jobs — use scheduled functions for cleanup and batch processing. These patterns cover most serverless use cases. Cloud Functions combine the convenience of serverless with the power of the Firebase ecosystem. They're the perfect place for business logic that needs Firebase access but shouldn't run on the client.
- Webhooks: Receive external webhooks and process them with Firebase.
- Email on Sign-up: Send welcome emails when new users sign up.
- Image Processing: Generate thumbnails and optimize images on upload.
- Data Aggregation: Compute daily/weekly statistics from application data.
- Scheduled Jobs: Run cleanup and batch processing on a schedule.
Knowledge Check
Ready to test your understanding of 8. Cloud Functions: Serverless Backend Logic?