Firebase webhooks are a way to receive real-time updates when specific events occur in your Firebase project. By setting up webhooks, you can automate workflows, trigger actions in other applications, and keep your systems in sync.
Before diving into examples, ensure that you have:
Let’s say you want to send a notification every time a new user registers. You can set up a webhook that triggers when a new user document is created in Firestore.
Steps:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.newUserNotification = functions.firestore
.document('users/{userId}')
.onCreate(async (snap, context) => {
const newValue = snap.data();
const payload = {
data: { userId: context.params.userId, ...newValue },
};
// Send the payload to your webhook endpoint
await sendToWebhook(payload);
});
async function sendToWebhook(payload) {
const webhookUrl = 'https://your-webhook-url.com/notify';
await fetch(webhookUrl, { method: 'POST', body: JSON.stringify(payload), headers: { 'Content-Type': 'application/json' }});
}
Webhook Endpoint: On your server, ensure you have an endpoint ready to handle incoming POST requests:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/notify', (req, res) => {
const userData = req.body;
console.log('New user registered:', userData);
// Process the data (e.g., send an email notification)
res.status(200).send('Notification received');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Another common use case is updating a user when their order status changes. Here’s how you can set this up:
Steps:
exports.orderStatusUpdate = functions.firestore
.document('orders/{orderId}')
.onUpdate(async (change, context) => {
const before = change.before.data();
const after = change.after.data();
if (before.status !== after.status) {
const payload = {
data: { orderId: context.params.orderId, newStatus: after.status },
};
await sendToWebhook(payload);
}
});
Webhook Handling: Similar to the user registration example, handle this data on your server:
app.post('/notify', (req, res) => {
const orderUpdate = req.body;
console.log('Order status updated:', orderUpdate);
// Update UI or send notifications accordingly
res.status(200).send('Order update received');
});
By using Firebase webhooks, you can easily set up real-time notifications and updates based on specific events in your application. The examples provided here demonstrate how to trigger actions based on user registrations and order status changes. Integrating these webhooks can enhance the responsiveness and interactivity of your applications.