Triggering Functions
Cloud Functions become truly powerful when they react to events happening in your Firebase services.
1. Firestore Triggers
You can listen to document creation, updates, and deletions.
// Trigger when a new document is created in "messages"
exports.onMessageCreate = functions.firestore
.document('messages/{messageId}')
.onCreate((snap, context) => {
const newValue = snap.data();
console.log('New message:', newValue.text);
});
2. Authentication Triggers
Useful for creating user profiles in Firestore immediately after registration.
exports.createUserAccount = functions.auth.user().onCreate((user) => {
// Logic to add user to Firestore
return admin.firestore().collection('users').doc(user.uid).set({
email: user.email,
createdAt: admin.firestore.FieldValue.serverTimestamp()
});
});
3. Storage Triggers
Triggered when a file is uploaded or deleted (e.g., to generate thumbnails).
exports.generateThumbnail = functions.storage.object().onFinalize((object) => {
// Logic to process the image
});
Key Benefit: Triggers allow you to decouple your frontend from complex background processing, ensuring a faster experience for your users.