Firebase Cloud Functions is a serverless backend for your Firebase app that allows you to run backend logic in response to events triggered by Firebase services and HTTPS requests.
* Event-driven execution – Respond to Firebase & Google Cloud events.
* Serverless – No need to manage infrastructure.
* Scalable – Automatically scales based on demand.
* Secure – Runs in an isolated cloud environment.
* Integrates with Firebase & external APIs – Can interact with Firestore, FCM, Auth, and more.
* Authentication Triggers – Send welcome emails when users sign up.
* Firestore Triggers – Validate or modify data when added/updated.
* FCM Triggers – Send push notifications on specific events.
* Scheduled Tasks – Run periodic jobs (e.g., cleanup inactive users).
* Custom APIs – Expose REST API endpoints for web & mobile apps.
npm install -g firebase-tools
firebase init functions
Open functions/index.js and add:
const functions = require("firebase-functions");
// Simple HTTP function
exports.helloWorld = functions.https.onRequest((req, res) => {
res.send("Hello from Firebase Cloud Functions!");
});
firebase deploy --only functions
Once deployed, Firebase provides a URL:
https://us-central1-YOUR_PROJECT.cloudfunctions.net/helloWorld
Open it in a browser or call it from a mobile app.
Send a push notification when a new document is added to Firestore.
const admin = require("firebase-admin");
const functions = require("firebase-functions");
admin.initializeApp();
exports.sendNotification = functions.firestore
.document("messages/{messageId}")
.onCreate(async (snap, context) => {
const messageData = snap.data();
const payload = {
notification: {
title: "New Message!",
body: messageData.text,
click_action: "FLUTTER_NOTIFICATION_CLICK"
}
};
return admin.messaging().sendToTopic("messages", payload);
});
| Trigger | Description |
|---|---|
| HTTPS Requests | Expose REST APIs (onRequest) |
| Firestore | Listen for document changes (onCreate, onUpdate, onDelete) |
| Authentication | React to user sign-ups or deletions (onCreate, onDelete) |
| Firebase Storage | Run functions on file uploads (onFinalize, onDelete) |
| Firebase Messaging (FCM) | Process push notifications (onMessagePublished) |
| Scheduled Functions | Run tasks on a cron schedule (pubsub.schedule) |
firebase functions:log).