Firebase Firestore provides real-time sync - when a new Instagram lead is captured, it appears instantly in any connected app (web dashboard, mobile app, admin panel). This guide shows you how to stream InstantDM events to Firestore.
Why Firebase?
- Real-time sync - data appears instantly in connected clients
- Free tier - 50K reads, 20K writes, 20K deletes per day
- Mobile SDKs - build iOS/Android apps that show Instagram leads in real-time
- Security rules - fine-grained access control
- Cloud Functions - trigger server-side logic on data changes
Webhook Receiver
const express = require('express');
const admin = require('firebase-admin');
const app = express();
app.use(express.json());
admin.initializeApp({
credential: admin.credential.cert(require('./service-account-key.json')),
});
const db = admin.firestore();
app.post('/webhook', async (req, res) => {
const { event, timestamp, data } = req.body;
try {
// Save to events collection
await db.collection('instagram_events').add({
event_type: event,
timestamp: admin.firestore.Timestamp.fromDate(new Date(timestamp)),
username: data.username,
instagram_user_id: data.instagram_user_id,
flow_name: data.flow_name || null,
lead_data: data.response_variables || null,
comment_text: data.comment_text || null,
message_text: data.message_text || null,
created_at: admin.firestore.FieldValue.serverTimestamp(),
});
// If it's a lead, also save to leads collection
if (event === 'flow_completed' && data.response_variables?.email) {
const leadRef = db.collection('leads').doc(data.response_variables.email);
await leadRef.set({
name: data.response_variables.full_name || data.username,
email: data.response_variables.email,
phone: data.response_variables.phone || null,
instagram: data.username,
interest: data.response_variables.interest || null,
flow_name: data.flow_name,
status: 'new',
updated_at: admin.firestore.FieldValue.serverTimestamp(),
}, { merge: true }); // merge to avoid overwriting existing data
}
res.status(200).json({ status: 'inserted' });
} catch (error) {
console.error('Firestore error:', error);
res.status(500).json({ status: 'error' });
}
});
app.listen(3000);
Real-Time Listener (Client-Side)
// In your web app or dashboard
import { collection, onSnapshot, query, orderBy, limit } from 'firebase/firestore';
const q = query(
collection(db, 'leads'),
orderBy('updated_at', 'desc'),
limit(50)
);
onSnapshot(q, (snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === 'added') {
console.log('New lead:', change.doc.data());
// Update your UI in real-time
}
});
});
Cloud Functions (Trigger on New Lead)
// functions/index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.onNewLead = functions.firestore
.document('leads/{email}')
.onCreate(async (snap, context) => {
const lead = snap.data();
// Send notification, update analytics, etc.
console.log(`New lead: ${lead.name} (${lead.email})`);
// Example: send FCM push notification to admin
await admin.messaging().send({
topic: 'new-leads',
notification: {
title: '🎯 New Instagram Lead',
body: `${lead.name} from @${lead.instagram}`,
},
});
});
Security Rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /leads/{email} {
allow read: if request.auth != null;
allow write: if false; // Only server can write
}
match /instagram_events/{eventId} {
allow read: if request.auth != null;
allow write: if false;
}
}
}
Troubleshooting
| Issue | Solution |
|---|---|
| Permission denied | Check Firestore security rules. Server writes use the Admin SDK which bypasses rules. |
| Service account error | Ensure the JSON key file path is correct and the file has proper permissions. |
| Real-time listener not updating | Check that the query matches the documents being written. Verify Firestore rules allow reads. |
| Hitting free tier limits | 50K reads/day is generous. If you exceed it, optimize queries or upgrade to Blaze plan. |
What's Next
- Set up PostgreSQL for SQL-based analytics.
- Connect to MongoDB for flexible document storage.
- Build Custom Dashboards with real-time data.
- Explore the full API docs at instantdm.com/instagram-api-docs.