Code me how to make a dashboard out of all the ad campaign metrics for one merchant in different services like amazon, google, swiggy, zomato, flipkart, etc. . In react, node, supabase db
Assistant
Of course! This is a fantastic project that touches on several key areas of modern web development. Building a unified ad campaign dashboard is a common and valuable business need.
I'll provide you with a comprehensive guide and code examples for setting up the entire stack: Supabase for the database, Node.js/Express for the backend API and data aggregation, and React for the frontend dashboard.
Let's break this down into a step-by-step plan.
The Core Challenge: Data Ingestion
The hardest part of this project isn't the code itself, but getting the data. Each platform (Amazon, Google, etc.) has a different API, authentication method, and data structure.
Platforms with Good APIs (e.g., Google Ads, Amazon Advertising): These have robust APIs that you can call from your Node.js backend to fetch data automatically. This is the ideal scenario.
Platforms without Public APIs (or with difficult-to-access ones): Swiggy, Zomato, and Flipkart may not offer public ad metric APIs for all merchants. In this case, the most practical solution is a CSV upload feature. The merchant downloads their campaign report from the platform and uploads it to your dashboard.
Our architecture will support both methods.
High-Level Architecture
Supabase (Database): A single table to store normalized campaign data from all sources.
Node.js (Backend):
Has scheduled jobs (cron jobs) to automatically fetch data from APIs like Google and Amazon.
Provides an API endpoint for the React app to fetch data for display.
Provides an API endpoint for manually uploading CSV files from other platforms.
React (Frontend):
Displays the data using charts, tables, and summary cards.
Allows the user to filter by date range and data source.
Once your project is ready, navigate to the SQL Editor.
Run the following SQL to create our main table. We're designing a "normalized" table where data from all sources will fit into a common structure.
sql
CREATE TABLE campaign_metrics (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
merchant_id UUID REFERENCES auth.users(id) NOT NULL, -- Link to a user if you have auth
source TEXT NOT NULL, -- 'google', 'amazon', 'swiggy', etc.
campaign_name TEXT,
report_date DATE NOT NULL,
impressions INT,
clicks INT,
spend NUMERIC(10, 2), -- For monetary values
sales NUMERIC(10, 2),
-- Add any other common metrics you want to track
-- e.g., conversions, ROAS (Return on Ad Spend), etc.
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- For performance, let's add indexes on columns we will filter by
CREATE INDEX ON campaign_metrics (merchant_id);
CREATE INDEX ON campaign_metrics (source);
CREATE INDEX ON campaign_metrics (report_date);
Go to Project Settings > API and copy your Project URL and anon public key. We'll need these for our Node.js and React apps.
Step 2: Building the Node.js Backend
This backend will be the engine of our dashboard, responsible for fetching, storing, and serving the data.
1. Project Setup
bash
mkdir marketing-dashboard-backend
cd marketing-dashboard-backend
npm init -y
npm install express cors dotenv @supabase/supabase-js node-cron multer csv-parser
# You would also install API-specific SDKs here
# npm install google-ads-api @sp-api-sdk/advertisingsponsoredproducts --save
2. Environment Variables
Create a .env file in the root of your backend project.
.env
SUPABASE_URL=YOUR_SUPABASE_PROJECT_URL
SUPABASE_KEY=YOUR_SUPABASE_ANON_KEY
# Add API keys for services here
# GOOGLE_ADS_CLIENT_ID=...
# AMAZON_SP_API_CLIENT_ID=...
3. Main Server File (index.js)
This file will set up the Express server, define the API endpoints, and contain the logic for data handling.
javascript
4. Run the Backend
bash
node index.js
Your backend is now running, ready to serve data and accept CSV uploads.
Step 3: Building the React Frontend
We'll use create-react-app and a charting library like Recharts for simplicity.
1. Project Setup
bash
npx create-react-app marketing-dashboard-frontend
cd marketing-dashboard-frontend
npm install axios recharts
2. Frontend Structure
Create a components folder inside src. We'll build a few components:
Dashboard.js: The main container.
KpiCard.js: To show single stats like "Total Spend".
// index.js
const express = require('express');
const cors = require('cors');
const { createClient } = require('@supabase/supabase-js');
const cron = require('node-cron');
const multer = require('multer');
const csv = require('csv-parser');
const fs = require('fs');
require('dotenv').config();
const app = express();
app.use(cors());
app.use(express.json());
const upload = multer({ dest: 'uploads/' }); // For CSV uploads
// Initialize Supabase
const supabaseUrl = process.env.SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_KEY;
const supabase = createClient(supabaseUrl, supabaseKey);
// --- AUTOMATED DATA FETCHING (Example Stubs) ---
// This function would contain the logic to fetch from Google Ads API
async function fetchGoogleAdsData() {
console.log('Fetching Google Ads data...');
// 1. Authenticate with Google Ads API using its SDK.
// 2. Query for campaign data for the last day.
// 3. Normalize the data to match our `campaign_metrics` table schema.
// Example normalized data:
const normalizedData = [
{
merchant_id: 'USER_UUID_HERE', // Replace with actual user ID
source: 'google',
campaign_name: 'Summer Sale Campaign',
report_date: new Date().toISOString().split('T')[0],
impressions: 15000,
clicks: 350,
spend: 50.75,
sales: 850.20,
},
];
// 4. Insert into Supabase
const { data, error } = await supabase.from('campaign_metrics').insert(normalizedData);
if (error) console.error('Error inserting Google Ads data:', error);
else console.log('Successfully inserted Google Ads data:', data);
}
// Stub for Amazon
async function fetchAmazonAdsData() {
console.log('Fetching Amazon Ads data...');
// Similar logic as Google Ads
}
// Schedule the tasks to run once a day
cron.schedule('0 2 * * *', () => { // Runs every day at 2 AM
console.log('Running daily data fetching cron job...');
fetchGoogleAdsData();
fetchAmazonAdsData();
});
// --- API ENDPOINTS FOR THE FRONTEND ---
// 1. GET Endpoint to fetch all metrics for the dashboard
app.get('/api/metrics', async (req, res) => {
// Add filtering by date range, source, etc. from query params
// e.g., /api/metrics?source=google&startDate=2023-01-01
const { data, error } = await supabase
.from('campaign_metrics')
.select('*')
.order('report_date', { ascending: false });
if (error) {
return res.status(500).json({ error: error.message });
}
res.status(200).json(data);
});
// 2. POST Endpoint for CSV Uploads (for Swiggy, Zomato, etc.)
app.post('/api/upload/csv', upload.single('file'), (req, res) => {
const source = req.body.source; // e.g., 'swiggy', 'zomato'
const filePath = req.file.path;
const results = [];
if (!source) {
return res.status(400).json({ error: 'Source platform is required.' });
}
fs.createReadStream(filePath)
.pipe(csv())
.on('data', (data) => {
// IMPORTANT: You must map the CSV columns to your DB schema here!
// This mapping will be different for each platform's CSV format.
const normalizedRow = {
merchant_id: 'USER_UUID_HERE', // Replace with actual user ID
source: source,
campaign_name: data['Campaign Name'], // Example column name
report_date: data['Date'],
impressions: parseInt(data['Impressions']),
clicks: parseInt(data['Clicks']),
spend: parseFloat(data['Cost']),
sales: parseFloat(data['Sales']),
};
results.push(normalizedRow);
})
.on('end', async () => {
const { data, error } = await supabase.from('campaign_metrics').insert(results);
fs.unlinkSync(filePath); // Clean up the uploaded file
if (error) {
return res.status(500).json({ error: error.message });
}
res.status(201).json({ message: 'CSV data imported successfully!', data });
});
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});