Blog
Getting Started with Firebase Cloud Functions
What are Cloud Functions?
Firebase Cloud Functions let you run backend code in response to events triggered by Firebase features and HTTPS requests.
They’re perfect for handling server-side logic without managing servers.
Lifecycle of a Cloud Function
Here’s a high-level flow of how a function runs:
flowchart TD
A[Event Triggered] --> B[Cloud Function Executes]
B --> C[Custom Logic Runs]
C --> D{Success?}
D -- Yes --> E[Return Response / Perform Action]
D -- No --> F[Error Handling & Logs]
F --> G[Retry or Fail Gracefully]
Setting Up Your First Function
Learn how to create, test, and deploy your first Firebase Cloud Function with practical examples.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
exports.addMessage = functions.https.onRequest(async (req, res) => {
const original = req.query.text;
const writeResult = await admin.firestore()
.collection('messages')
.add({ original: original });
res.json({ result: `Message with ID: ${writeResult.id} added.` });
});
Common Use Cases
Cloud Functions are ideal for:
- Data processing
- Sending notifications
- Image resizing
- Integrating with third-party services
Types of Triggers
Here’s a quick comparison of the main types of triggers you can use:
| Trigger Type | Example Use Case | Example Code Snippet |
|---|---|---|
| HTTP | Expose REST APIs, process forms | functions.https.onRequest(...) |
| Firestore | React to DB changes | functions.firestore.document(...).onCreate(...) |
| Auth | Run code on user signup | functions.auth.user().onCreate(...) |
| Storage | Process uploaded images/files | functions.storage.object().onFinalize(...) |
| Pub/Sub | Scheduled jobs, async tasks | functions.pubsub.schedule('every 24h').onRun(...) |
Database Triggers
Example: run when a new user document is created.
exports.onUserCreate = functions.firestore
.document('users/{userId}')
.onCreate(async (snap, context) => {
const userData = snap.data();
// Send welcome email
await sendWelcomeEmail(userData.email);
// Create user profile
await admin.firestore().collection('profiles')
.doc(context.params.userId)
.set({
createdAt: admin.firestore.FieldValue.serverTimestamp(),
displayName: userData.displayName
});
});
HTTP Functions
Handle HTTPS requests directly, including CORS:
exports.processPayment = functions.https.onRequest(async (req, res) => {
// CORS handling
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'POST');
res.set('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') {
res.status(204).send('');
return;
}
try {
const { amount, token } = req.body;
// Process payment logic here
const result = await processStripePayment(amount, token);
res.json({ success: true, transactionId: result.id });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
Conclusion
Firebase Cloud Functions provide a powerful way to add server-side logic to your applications without managing infrastructure.
Start with simple HTTP functions, then gradually explore advanced features like database triggers and scheduled functions.
Enjoyed this? Share it, or reply by email — comments are retired here to keep the site fast and low-maintenance.