Understanding Firebase Webhooks for Real-Time Data Updates

In this article, we'll explore how Firebase webhooks can be utilized to receive real-time updates on data changes. We'll provide clear examples and practical applications to help you understand how to implement webhooks in your projects effectively.
By Jamie

What are Firebase Webhooks?

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.

Setting Up Firebase Webhooks

Before diving into examples, ensure that you have:

  • A Firebase project set up.
  • A server endpoint ready to receive HTTP POST requests.

Example 1: User Registration Notification

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:

  1. Create a Firestore Trigger: In your Firebase Cloud Functions, you can set up a Firestore trigger like so:

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' }});
}

  1. 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');
    });
    

Example 2: Order Status Update

Another common use case is updating a user when their order status changes. Here’s how you can set this up:

Steps:

  1. Create another Firestore Trigger: This time, you’ll listen for changes in an orders collection:

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);
        }
    });

  1. 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');
    });
    

Conclusion

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.