How To Set Up GA4 Custom Alerts for Specific Conversions with Apps Script
Introduction
In Google Analytics 4 (GA4), Custom Insights (formerly known as custom alerts) serve as proactive notifications that help users monitor significant changes in data patterns, such as unusual drops in conversion rates. These insights are crucial for marketers and analysts to react swiftly to emerging trends or potential issues. However, GA4 currently limits users to setting alerts for overall conversions without the ability to drill down into specific conversions (now called Key Actions). This restriction can be problematic for businesses that require detailed analyses of particular conversion drops to make informed decisions quickly. In this article, I will introduce a method utilizing Google App Script, enabling you to bypass this limitation by setting up custom alerts tailored to individual conversion events, providing the granular control needed for effective data monitoring.
Overview of the Solution
To enhance monitoring capabilities in GA4 for specific conversion events, we will use a Google App Script that automates custom alerts. The script, scheduled to run monthly, operates as follows:
- Data Retrieval: It calls the Google Analytics Data API twice; first, to obtain conversion numbers from the previous month, and second, to acquire similar data from the month before that.
- Change Calculation: It computes the percentage change in conversions by using the formula ($\text{current} - \text{last}) / \text{last} \times 100)$.
- Alert Activation: If the percentage drop in conversions surpasses a predefined threshold, the script automatically sends a notification via the Gmail API.
This tailored script ensures you receive timely and specific data on conversion trends, facilitating immediate response and strategic decision-making for your business.
Prerequisites
Before implementing the customized alert script in Google App Script, ensure the following prerequisites are met:
- Google Account: You must have a Google account as it is required to access and utilize Google App Script and other Google APIs (i.e. Google Analytics Data API & Gmail API).
- Access to Google Analytics: Your Google account should have read access to the Google Analytics property from which you desire to extract conversion data. This is essential for making API calls to retrieve the necessary metrics.
- GA4 Property ID and Conversion Event Name: You also need to have GA4 Property ID and name of the conversion that you wish to track. You can find your Project ID in your Google Analytics Property. Go to Admin -> under “Property,” click on “Property Settings.” There, you should be able to see your Property ID displayed.
Setting Up Your Google App Script Environment
Follow these steps to create and prepare your Google App Script for custom GA4 alerts:
- Create a Google Sheet:
- Navigate to your Google Drive.
- Create a dedicated folder named “AppScript” for organizational purposes.
- Inside this folder, create a new Google Sheet and name it “GA4 Custom Alerts”.
- Access App Script:
- Open the Google Sheet you just created.
- Go to Extensions -> Apps Script to open the script editor.
- Inside the Apps Script, rename the project to “GA4 Custom Alerts Script” for consistency.
- Enable APIs:
- In the Apps Script editor, click the + button next to “Services.”
- From the menu, add “Google Analytics Data API” and “Gmail API” to your project.
- Create Script Files:
- To organize your code, create four separate script files by clicking the + next to “Files” and selecting “Script.”
- Name these scripts as follows: “main”, “sendEmailNotification”, “conversionsForFirstPeriod”, and “conversionsForSecondPeriod”.
- In the appendix, you’ll discover code snippets along with descriptions of what they achieve. For each snippet, there are directives on the necessary modifications to be made by you, which are outlined below each piece of code. Please make changes as needed and insert the modified code snippets into the corresponding script files within Apps Script.
- Test Scripts:
- Verify that the
sendEmailNotification
function is operational by testing it with dummy data to ensure it can send emails successfully. - Confirm that the
conversionsForFirstPeriod
function is able to pull data accurately. Navigate to your GA4 Property, set up a Custom Exploration, and ensure the data retrieved matches expectations. - Repeat the above validation for the
conversionsForSecondPeriod
function to ensure it also retrieves data correctly. - Test the
main
function to make sure it performs as intended. Check that the calculations are accurate and assess if it triggers an email alert when the conversion drop meets the specified criteria.
- Verify that the
- Set Up a Scheduled Trigger:
- Navigate to “Triggers” in the AppScript menu, represented by an alarm clock icon on the left side. Click “Add Trigger” and select “main” from the list of functions to execute. For the event source, choose “Time-driven” and then select “Month timer” for the type of time-based trigger. Configure it to execute, for example, on the 15th day of each month between 4 and 5 PM. Once you are happy with the configurations, click on “Save” to activate the trigger.
Conclusion
I hope this guide proves to be a valuable resource as you navigate the setup of custom alerts in GA4 using Google App Script. We encourage you to explore the capabilities of App Script further; it’s a powerful tool for automation, especially for tasks involving Google products.
Remember, while this guide provides a foundation, always refer to the official Google documentation for the most current and detailed information. It’s crucial to conduct your own due diligence and thoroughly test your scripts in a controlled environment before implementing them in a live setting. This proactive approach will help ensure the effectiveness and reliability of your automation tasks, leading to smoother operations and more informed decision-making. If you find the content helpful, please like the article so that more people know about it and it can help someone else.
Appendix: Code Snippets
Overview of main
Function
The main
function orchestrates the entire process of calculating the percentage change in a specified conversion event over two consecutive months and sends an email notification if there is a significant drop. It relies on data gathered by conversionsForFirstPeriod
and conversionsForSecondPeriod
.
The code snippet for the main
function is as follows:
function main() {
const conversionLastMonth = conversionsForFirstPeriod();
const conversionMonthBefore = conversionsForSecondPeriod();
console.log(`Last month we have ${conversionLastMonth} conversions, one month before we got ${conversionMonthBefore}`);
const percentChangeInConversions = Math.round(((conversionLastMonth - conversionMonthBefore) / conversionMonthBefore) * 100);
console.log(`The percent change in conversions is ${percentChangeInConversions}`);
if(percentChangeInConversions < -10){
sendEmailNotification("RECEPIENT-EMAIL", "YOUR-CONVERSION-EVENT-NAME", percentChangeInConversions);
}
}
Please fill the following: “RECEPIENT-EMAIL”, “YOUR-CONVERSION-EVENT-NAME”.
Function Breakdown:
- Retrieve Conversion Data:
- Calls
conversionsForFirstPeriod
andconversionsForSecondPeriod
to obtain conversion counts for the last month and the month before, respectively.
- Calls
- Calculate Percentage Change:
- Computes the percentage change in conversions using formula provided above
- Rounds off the value to the nearest whole number for better readability.
- Log and Analyze Change:
- Logs the conversion counts and their percentage change to provide immediate feedback regarding the fluctuations in the console.
- Conditional Alerting:
- Checks if the computed percentage drop in conversions exceeds -10%. If this condition is met, it triggers an email alert by invoking
sendEmailNotification
with details including the recipient’s email, event name, and the percentage drop.
- Checks if the computed percentage drop in conversions exceeds -10%. If this condition is met, it triggers an email alert by invoking
Overview of sendEmailNotification
Function
This function effectively notifies stakeholders of significant changes in conversion metrics, enhancing responsiveness to potential issues in digital marketing efforts.
The code snippet of “emailSender” is the following:
function sendEmailNotification(emailRecipient, conversionName, dropPercentage) {
const subject = 'GA4 Conversion Alert: Conversion Drop Detected';
const body = `Conversion ${conversionName} are dropped by ${dropPercentage}% in the last 30 days compared 30 days before that.`;
GmailApp.sendEmail(emailRecipient, subject, body);
}
There is nothing to fill here from your side
The sendEmailNotification
function in the script serves the following primary purposes:
- Email Preparation:
- Takes three inputs:
emailRecipient
(which can be a single email address or a comma-separated list of multiple addresses),conversionName
(the name of the conversion event being monitored), anddropPercentage
(the calculated drop in conversions expressed as a percentage).
- Takes three inputs:
- Email Composition:
- Constructs the email with a predefined subject line: ‘GA4 Conversion Alert: Conversion Drop Detected’.
- Formulates an informative body message that details the specific conversion drop, stating which conversion has dropped and by what percentage over the last month compared to the previous one.
- Sending the Email:
- Utilizes the
GmailApp.sendEmail
method to dispatch the email to the specified recipient(s).
- Utilizes the
Overview of conversionsForFirstPeriod
Function
This function is designed to fetch the count of a specific conversion event over the past 30 days. It effectively helps in monitoring changes in the specific event’s performance, offering critical data for comparison purposes.
The code snippet of “conversionsForFirstPeriod” is as follows:
function conversionsForFirstPeriod() {
const propertyId = 'YOUR-GA4-PROPERTY-ID';
try {
const metric = AnalyticsData.newMetric();
metric.name = 'eventCount';
const dimension = AnalyticsData.newDimension();
dimension.name = 'eventName';
const dateRange = AnalyticsData.newDateRange();
dateRange.startDate = '30daysAgo';
dateRange.endDate = 'yesterday';
const dimensionFilter = AnalyticsData.newFilter();
dimensionFilter.fieldName = 'eventName';
dimensionFilter.stringFilter = {
matchType: 'EXACT',
value: 'YOUR-CONVERSION-EVENT-NAME'
};
const filterExpression = AnalyticsData.newFilterExpression();
filterExpression.filter = dimensionFilter;
const request = AnalyticsData.newRunReportRequest();
request.dimensions = [dimension];
request.metrics = [metric];
request.dateRanges = [dateRange];
request.dimensionFilter = filterExpression;
const report = AnalyticsData.Properties.runReport(request,
'properties/' + propertyId);
if (!report.rows) {
console.log('No rows returned.');
return;
}
report.rows.forEach(row => {
const eventName = row.dimensionValues[0].value;
const eventCount = row.metricValues[0].value;
console.log(`Event Name: ${eventName}, Count: ${eventCount}`);
});
return report.rows[0].metricValues[0].value;
} catch (e) {
console.log('Failed with error: %s', e.error);
}
}
Please fill the following: ‘YOUR-GA4-PROPERTY-ID’, ‘YOUR-CONVERSION-EVENT-NAME’
Function Breakdown:
- Setting up the API request:
- Initializes metric and dimension to focus the query on the count of events by their names.
- Sets the date range for the last 30 days.
- Applies a filter to extract data for a specific conversion event.
- Executing the API Call:
- Forms and sends the API request using the constructed parameters, targeting the specified GA4 property ID.
- Handling the API Response:
- Checks for and processes the returned data, extracting the count of the specified event.
- Logs each occurrence of the event alongside its count for review.
- Error Handling:
- Captures and logs any errors that occur during the API request or data processing.
Overview of conversionsForSecondPeriod
Function
This function is tailored to retrieve the count of a specific conversion event from the prior period, specifically from 60 to 31 days ago. It is crucial for comparative analysis, providing a baseline to measure changes against recent data.
The code snippet of “conversionsForSecondPeriod” is as follows:
function conversionsForSecondPeriod() {
const propertyId = 'YOUR_GA4_PROPERTY_ID';
try {
const metric = AnalyticsData.newMetric();
metric.name = 'eventCount';
const dimension = AnalyticsData.newDimension();
dimension.name = 'eventName';
const dateRange = AnalyticsData.newDateRange();
dateRange.startDate = '60daysAgo';
dateRange.endDate = '31daysAgo';
const dimensionFilter = AnalyticsData.newFilter();
dimensionFilter.fieldName = 'eventName';
dimensionFilter.stringFilter = {
matchType: 'EXACT',
value: 'YOUR CONVERSION EVENT NAME'
};
const filterExpression = AnalyticsData.newFilterExpression();
filterExpression.filter = dimensionFilter;
const request = AnalyticsData.newRunReportRequest();
request.dimensions = [dimension];
request.metrics = [metric];
request.dateRanges = [dateRange];
request.dimensionFilter = filterExpression;
const report = AnalyticsData.Properties.runReport(request,
'properties/' + propertyId);
if (!report.rows) {
console.log('No rows returned.');
return;
}
report.rows.forEach(row => {
const eventName = row.dimensionValues[0].value;
const eventCount = row.metricValues[0].value;
console.log(`Event Name: ${eventName}, Count: ${eventCount}`);
});
return report.rows[0].metricValues[0].value;
} catch (e) {
console.log('Failed with error: %s', e.error);
}
}
Please fill the following: ‘YOUR-GA4-PROPERTY-ID’, ‘YOUR-CONVERSION-EVENT-NAME’
Function Breakdown:
- Setting up the API request:
- Initializes the necessary metric and dimension to focus the query on counting events by their names.
- Adjusts the date range to target data from 60 to 31 days ago, providing a snapshot of the previous period.
- Applies a specific event filter to ensure the data pertains solely to the targeted conversion event.
- Executing the API Call:
- Forms and dispatches the API request using the defined parameters, aimed at the specified GA4 property ID.
- Handling the API Response:
- Verifies and processes the received data, extracting the count for the specified event during the defined historical period.
- Iteratively logs each event name alongside its count for detailed examination.
- Error Handling:
- Captures and reports on any errors encountered throughout the API request or data processing steps.
If you found this article useful and would like to support my work, consider buying me a coffee! Just click on the button below and follow the instructions to make a donation. Your support helps me create more valuable content. Thank you!