Build powerful product analytics with Lovable. Uncover actionable insights, drive smart decisions, and fuel growth to achieve product excellence.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Setting Up Your Lovable Product Analytics Project
index.html
file, a JavaScript file (for example, main.js
), and a place to add configuration files.
Adding the Lovable Analytics Dependency
index.html
file and insert the following script tag inside the <head>
section to load the Lovable analytics library from their CDN:
<script src="https://cdn.lovable.com/analytics.min.js"></script>
Creating the Lovable Configuration File
lovable.config.js
.YOUR_LOVABLE_API_KEY
and YOUR_PRODUCT\_ID
with your actual API key and product ID:
window.lovableConfig = {
apiKey: "YOUR_LOVABLE_API\_KEY",
productId: "YOUR_PRODUCT_ID",
environment: "production" // Use "development" for testing purposes if needed
};
Including the Configuration in Your HTML
index.html
file, include the configuration file right after you include the Lovable analytics script. Your <head>
section should now look like this:
<head>
<script src="https://cdn.lovable.com/analytics.min.js"></script>
<script src="lovable.config.js"></script>
<!-- Other head elements go here -->
</head>
Initializing Lovable Analytics
main.js
, where you manage your app’s startup routines.
document.addEventListener("DOMContentLoaded", function() {
// Check to make sure the configuration is loaded
if (window.lovableConfig) {
// Initialize Lovable Analytics using the configuration values
Lovable.init(window.lovableConfig);
} else {
console.error("Lovable configuration not found!");
}
});
Tracking Product Events
main.js
file:
function trackProductView(product) {
Lovable.track("Product Viewed", {
productId: product.id,
name: product.name,
category: product.category
});
}
// Example: Call this function when the product page loads
document.addEventListener("DOMContentLoaded", function() {
var currentProduct = {
id: "12345",
name: "Amazing Gadget",
category: "Electronics"
};
trackProductView(currentProduct);
});
Tracking User Interactions
main.js
or relevant script file:
document.getElementById("addToCartBtn").addEventListener("click", function() {
// Assume product details are available
var product = {
id: "12345",
name: "Amazing Gadget",
category: "Electronics"
};
Lovable.track("Add to Cart", {
productId: product.id,
name: product.name
});
});
addToCartBtn
exists in your HTML file.
Verifying and Testing Your Integration
Updating and Expanding Analytics
Lovable.track
with an event name and attach it to the appropriate event handler in your application.
Final Checks and Going Live
index.html
, lovable.config.js
, and main.js
files to confirm that the correct code snippets are in place.
const express = require('express');
const bodyParser = require('body-parser');
const { MongoClient } = require('mongodb');
const app = express();
app.use(bodyParser.json());
const uri = 'mongodb://localhost:27017';
let db;
MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
.then(client => {
db = client.db('lovable_product_analytics');
console.log('Connected to MongoDB');
})
.catch(err => {
console.error('Failed to connect to MongoDB', err);
process.exit(1);
});
// API endpoint to ingest product analytics events
app.post('/api/v1/product-events', async (req, res) => {
const { productId, eventType, timestamp, userData, additionalData } = req.body;
if (!productId || !eventType || !timestamp) {
return res.status(400).json({ error: 'Missing required fields: productId, eventType, or timestamp' });
}
// Structured data document for analytics event
const analyticsEvent = {
productId,
eventType,
timestamp: new Date(timestamp),
userData: userData || {},
additionalData: additionalData || {},
receivedAt: new Date()
};
try {
const result = await db.collection('analytics\_events').insertOne(analyticsEvent);
res.status(201).json({ message: 'Event logged successfully', eventId: result.insertedId });
} catch (error) {
console.error('Error inserting analytics event:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
const { Pool } = require('pg');
const app = express();
app.use(bodyParser.json());
const pool = new Pool({
connectionString: process.env.DATABASE_URL || 'postgres://user:password@localhost:5432/lovable_analytics'
});
const EXTERNAL_PRODUCT_API = 'https://api.external-productinfo.com/v2/products';
// Endpoint to ingest product analytics events with external data enrichment
app.post('/api/v1/enriched-events', async (req, res) => {
const { productId, eventType, timestamp, userData } = req.body;
if (!productId || !eventType || !timestamp) {
return res.status(400).json({ error: 'Missing required fields: productId, eventType, or timestamp' });
}
try {
// Call external product API to enrich event data
const response = await axios.get(`${EXTERNAL_PRODUCT_API}/${productId}`);
const productInfo = response.data;
const enrichedEvent = {
product\_id: productId,
event\_type: eventType,
event\_timestamp: new Date(timestamp),
user\_data: userData || {},
product\_info: productInfo,
received\_at: new Date()
};
const query = \`
INSERT INTO product_events (product_id, event_type, event_timestamp, user_data, product_info, received\_at)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id
\`;
const values = [
enrichedEvent.product\_id,
enrichedEvent.event\_type,
enrichedEvent.event\_timestamp,
enrichedEvent.user\_data,
enrichedEvent.product\_info,
enrichedEvent.received\_at
];
const result = await pool.query(query, values);
res.status(201).json({ message: 'Enriched event logged successfully', eventId: result.rows[0].id });
} catch (error) {
console.error('Error processing enriched event:', error.message);
res.status(500).json({ error: 'Internal Server Error' });
}
});
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
const { ApolloServer, gql } = require('apollo-server');
const { createClient } = require('redis');
const { MongoClient } = require('mongodb');
const typeDefs = gql\`
scalar JSON
type AnalyticsEvent {
id: ID!
productId: String!
eventType: String!
timestamp: String!
meta: JSON
}
type Mutation {
logEvent(productId: String!, eventType: String!, timestamp: String!, meta: JSON): AnalyticsEvent
}
type Query {
events: [AnalyticsEvent]
}
\`;
const resolvers = {
JSON: require('graphql-type-json'),
Query: {
events: async (_, _\_, { db }) => {
return await db.collection('analytics\_events').find().toArray();
},
},
Mutation: {
logEvent: async (\_, args, { db, redisClient }) => {
const analyticsEvent = {
productId: args.productId,
eventType: args.eventType,
timestamp: new Date(args.timestamp),
meta: args.meta || {},
createdAt: new Date()
};
const result = await db.collection('analytics\_events').insertOne(analyticsEvent);
redisClient.publish('analyticsEvents', JSON.stringify(analyticsEvent));
analyticsEvent.id = result.insertedId;
return analyticsEvent;
}
}
};
(async () => {
const mongoClient = new MongoClient('mongodb://localhost:27017', { useUnifiedTopology: true });
await mongoClient.connect();
const db = mongoClient.db('lovable_product_analytics');
const redisClient = createClient();
await redisClient.connect();
const server = new ApolloServer({
typeDefs,
resolvers,
context: () => ({ db, redisClient })
});
server.listen({ port: 5000 }).then(({ url }) => {
console.log(`GraphQL API running at ${url}`);
});
})();
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Overview
Understanding Product Analytics and AI Code Generators
Planning Your Analytics Product
Integrating AI Code Generators
Connect to MySQL database using credentials: host, user, password, and database name.
Testing and Validation
console.log("Data point recorded:", dataPoint);
Deployment and Maintenance
Monitoring and Iteration
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.