Google Analytics 4 (GA4) offers a robust way to track user interactions and events in your web application. Whether it's user actions, purchases, or subscription details, integrating GA4 can help gather useful insights. This guide will walk you through setting up GA4 event tracking in a frontend React.js application with a Node.js backend.
Step 1: Setting Up GA4 in React.js
To track user interactions in your React frontend, you’ll need the react-ga4 package, which acts as a wrapper around Google Analytics' API. Here’s how you can set up and trigger custom GA4 events.
import ReactGA from 'react-ga4';
const sendCustomGA4Event = async (category, action, label, userID, otherDetails = {}, email = '') => {
ReactGA.initialize(process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_ID as string);
try {
ReactGA.event({
category,
action,
label,
});
console.log('GA4 event sent successfully');
} catch (error) {
console.error('Error sending GA4 event:', error);
}
};
export default sendCustomGA4Event;
Step 2: Setting Up GA4 in Node.js Backend
For backend event tracking—such as when a payment is processed or a subscription is created—we can send events to GA4 using Google Analytics’ Measurement Protocol.
import axios from 'axios';
import config from './config'; // Config contains your GA4 secrets
import { v4 as uuidv4 } from 'uuid';
const sendGA4Event = async (eventName, eventParams) => {
const clientId = uuidv4();
const data = {
client_id: clientId,
events: [
{
name: eventName,
params: eventParams,
},
],
};
try {
const response = await axios.post(
`https://www.google-analytics.com/mp/collect?measurement_id=${config.GA4_MEASUREMENT_ID}&api_secret=${config.GA4_API_SECRET}`,
data,
{ headers: { 'Content-Type': 'application/json' } }
);
console.log('GA4 event tracked successfully:', response.data);
} catch (error) {
console.error('Error sending GA4 event:', error);
}
};
export default sendGA4Event;
Step 3: Event Parameters
When sending GA4 events, make sure your event parameters are detailed. Here’s an example of how event parameters might look:
const eventParams = {
currency: 'USD',
payment_method: 'credit_card',
value: 49.99,
plan_duration: '1 year',
plan_name: 'Pro Plan',
tax: 5,
transaction_id: 'abc123',
plan_type: 'annual',
is_free_trial: false,
items: [
{
item_id: 'plan123',
item_name: 'Pro Plan',
price: 49.99,
plan_duration: '1 year',
quantity: 1,
},
],
};
Conclusion
By integrating GA4 into both your frontend and backend, you can capture a comprehensive range of events and user behaviors. This setup will allow you to track specific user interactions, ensuring your analytics data reflects both frontend and backend activities.
Start by setting up custom events in React, and then expand your tracking capabilities with backend events using the Google Analytics Measurement Protocol. Happy tracking!
0 Comments
Post a Comment