Google Analytics is nice, however not everybody in your group will probably be granted entry. In lots of locations I’ve labored, it was on a form of “have to know” foundation.
On this article, I’m gonna flip that on its head and present you the way I wrote a GitHub Motion that queries Google Analytics, generates a prime ten record of probably the most continuously seen pages on my web site from the final seven days and compares them to the earlier seven days to inform me which pages have elevated in views, which pages have decreased in views, which pages have stayed the identical and which pages are new to the record.
The report is then properly formatted with icon indicators and posted to a public Slack channel each Friday at 10 AM.
Not solely would this surfaced knowledge be helpful for people who would possibly want it, nevertheless it additionally supplies a straightforward strategy to copy and paste or screenshot the report and add it to a slide for the weekly firm/division assembly.
Right here’s what the completed report appears to be like like in Slack, and under, you’ll discover a hyperlink to the GitHub Repository.
GitHub
To make use of this repository, observe the steps outlined within the README.
https://github.com/PaulieScanlon/smashing-weekly-analytics
Conditions
To construct this workflow, you’ll want admin entry to your Google Analytics and Slack Accounts and administrator privileges for GitHub Actions and Secrets and techniques for a GitHub repository.
Customizing the Report and Motion
Naturally, the entire code might be modified to fit your necessities, and within the following sections, I’ll clarify the areas you’ll seemingly need to check out.
Customizing the GitHub Motion
The file identify of the Motion weekly-analytics.report.yml isn’t seen wherever apart from within the code/repo however naturally, change it to no matter you want, you gained’t break something.
The identify and jobs: names detailed under are seen within the GitHub UI and Workflow logs.
The cron syntax determines when the Motion will run. Schedules use POSIX cron syntax and by altering the numbers you may decide when the Motion runs.
You could possibly additionally change the secrets and techniques variable names; simply be sure to replace them in your repository Settings.
identify: Weekly Analytics Report
on:
schedule:
– cron: ‘0 10 * * 5’ # Runs each Friday at 10 AM UTC
workflow_dispatch: # Permits handbook triggering
jobs:
analytics-report:
runs-on: ubuntu-latest
env:
SLACK_WEBHOOK_URL: ${{ secrets and techniques.SLACK_WEBHOOK_URL }}
GA4_PROPERTY_ID: ${{ secrets and techniques.GA4_PROPERTY_ID }}
GOOGLE_APPLICATION_CREDENTIALS_BASE64: ${{ secrets and techniques.GOOGLE_APPLICATION_CREDENTIALS_BASE64 }}
steps:
– identify: Checkout repository
makes use of: actions/checkout@v4
– identify: Setup Node.js
makes use of: actions/setup-node@v4
with:
node-version: ’20.x’
– identify: Set up dependencies
run: npm set up
– identify: Run the JavaScript script
run: node src/companies/weekly-analytics.js
Customizing the Google Analytics Report
The Google Analytics API request I’m utilizing is ready to drag the fullPageUrl and pageTitle for the totalUsers within the final seven days, and a second request for the earlier seven days, after which aggregates the totals and limits the responses to 10.
You need to use Google’s GA4 Question Explorer to assemble your individual question, then change the requests.
// src/companies/weekly-analytics.js#L75
const [thisWeek] = await analyticsDataClient.runReport({
property: `properties/${course of.env.GA4_PROPERTY_ID}`,
dateRanges: [
{
startDate: ‘7daysAgo’,
endDate: ‘today’,
},
],
dimensions: [
{
name: ‘fullPageUrl’,
},
{
name: ‘pageTitle’,
},
],
metrics: [
{
name: ‘totalUsers’,
},
],
restrict: reportLimit,
metricAggregations: [‘MAXIMUM’],
});
Creating the Comparisons
There are two features to find out which web page views have elevated, decreased, stayed the identical, or are new.
The primary is a straightforward cut back perform that returns the URL and a rely for every.
const { url, rely } = merchandise;
gadgets[url] = rely;
return gadgets;
}, {});
The second maps over the outcomes from this week and compares them to final week.
const report = thisWeekResults.map((merchandise, index) => {
const { url, title, rely } = merchandise;
const lastWeekCount = lastWeekMap[url];
const standing = determineStatus(rely, lastWeekCount);
return {
place: (index + 1).toString().padStart(2, ‘0’), // Format the place with main zero if it is lower than 10
url,
title,
rely: ‘0’ , // Guarantee lastWeekCount is displayed as ‘0’ if not discovered
standing,
};
});
The ultimate perform is used to find out the standing of every.
// Perform to find out the standing
const determineStatus = (rely, lastWeekCount) => {
const thisCount = Quantity(rely);
const previousCount = Quantity(lastWeekCount);
if (lastWeekCount === undefined || lastWeekCount === ‘0’) {
return NEW;
}
if (thisCount > previousCount) {
return HIGHER;
}
if (thisCount < previousCount) {
return LOWER;
}
return SAME;
};
I’ve purposely left the code pretty verbose, so it’ll be simpler so that you can add console.log to every of the features to see what they return.
Customizing the Slack Message
The Slack message config I’m utilizing creates a heading with an emoji, a divider, and a paragraph explaining what the message is.
Under that I’m utilizing the context object to assemble a report by iterating over comparisons and returning an object containing Slack particular message syntax which incorporates an icon, a rely, the identify of the web page and a hyperlink to every merchandise.
You need to use Slack’s Block Equipment Builder to assemble your individual message format.
const slackList = report.map((merchandise, index) => {
const {
place,
url,
title,
rely: { thisWeek, lastWeek },
standing,
} = merchandise;
return {
kind: ‘context’,
parts: [
{
type: ‘image’,
image_url: ${reportConfig.url}/images/${status},
alt_text: ‘icon’,
},
{
type: ‘mrkdwn’,
text: ${position}. <${url}|${title}> | *${x${thisWeek}}`* / x${lastWeek}`,
},
],
};
});
Earlier than you may run the GitHub Motion, you will have to finish a variety of Google, Slack, and GitHub steps.
Able to get going?
Making a Google Cloud Venture
Head over to your Google Cloud console, and from the dropdown menu on the prime of the display screen, click on Choose a undertaking, and when the modal opens up, click on NEW PROJECT.
Venture identify
On the following display screen, give your undertaking a reputation and click on CREATE. In my instance, I’ve named the undertaking smashing-weekly-analytics.
Allow APIs & Companies
On this step, you’ll allow the Google Analytics Information API to your new undertaking. From the left-hand sidebar, navigate to APIs & Companies > Allow APIs & companies. On the prime of the display screen, click on + ENABLE APIS & SERVICES.
Allow Google Analytics Information API
Seek for “Google analytics knowledge API,” choose it from the record, then click on ENABLE.
Create Credentials for Google Analytics Information API
With the API enabled in your undertaking, now you can create the required credentials. Click on the CREATE CREDENTIALS button on the prime proper of the display screen to arrange a brand new Service account.
A Service account permits an “software” to work together with Google APIs, offering the credentials embody the required companies. On this instance, the credentials grant entry to the Google Analytics Information API.
Service Account Credentials Sort
On the following display screen, choose Google Analytics Information API from the dropdown menu and Software knowledge, then click on NEXT.
Service Account Particulars
On the following display screen, give your Service account a identify, ID, and description (optionally available). Then click on CREATE AND CONTINUE.
In my instance, I’ve given my service account a reputation and ID of smashing-weekly-analytics and added a brief description that explains what the service account does.
Service Account Position
On the following display screen, choose Proprietor for the Position, then click on CONTINUE.
Service Account Achieved
You’ll be able to depart the fields clean on this final step and click on DONE while you’re prepared.
Service Account Keys
From the left-hand navigation, choose Service Accounts, then click on the “extra dots” to open the menu and choose Handle keys.
Service Accounts Add Key
On the following display screen, find the KEYS tab on the prime of the display screen, then click on ADD KEY and choose Create new key.
Service Accounts Obtain Keys
On the following display screen, choose JSON as the important thing kind, then click on CREATE to obtain your Google Software credentials .json file.
Google Software Credentials
For those who open the .json file in your code editor, you need to be one thing much like the one under.
In case you’re questioning, no, you may’t use an object as a variable outlined in an .env file. To make use of these credentials, it’s essential to convert the entire file right into a base64 string.
Notice: I wrote a extra detailed submit about learn how to use Google Software credentials as surroundings variables right here: “The way to Use Google Software .json Credentials in Surroundings Variables.”
Out of your terminal, run the next: change name-of-creds-file.json with the identify of your .json file.
cat name-of-creds-file.json | base64
For those who’ve already cloned the repo and adopted the Getting began steps within the README, add the base64 string returned after operating the above and add it to the GOOGLE_APPLICATION_CREDENTIALS_BASE64 variable in your .env file, however be sure to wrap the string with double citation makes.
GOOGLE_APPLICATION_CREDENTIALS_BASE64=”abc123″
That completes the Google undertaking facet of issues. The following step is so as to add your service account e-mail to your Google Analytics property and discover your Google Analytics Property ID.
Google Analytics Properties
While your service account now has entry to the Google Analytics Information API, it doesn’t but have entry to your Google Analytics account.
Get Google Analytics Property ID
To make queries to the Google Analytics API, you’ll have to know your Property ID. You could find it by heading over to your Google Analytics account. Be sure to’re on the right property (within the screenshot under, I’ve chosen paulie.dev — GA4).
Click on the admin cog within the backside left-hand facet of the display screen, then click on Property particulars.
On the following display screen, you’ll see the PROPERTY ID within the prime proper nook. For those who’ve already cloned the repo and adopted the Getting began steps within the README, add the property ID worth to the GA4_PROPERTY_ID variable in your .env file.
Add Shopper E mail to Google Analytics
From the Google software credential .json file you downloaded earlier, find the client_email and replica the e-mail handle.
In my instance, it appears to be like like this: smashing-weekly-analytics@smashing-weekly-analytics.iam.gserviceaccount.com.
Now navigate to Property entry administration from the left disguise facet navigation and click on the + within the prime right-hand nook, then click on Add customers.
On the following display screen, add the client_email to the E mail addresses enter, uncheck Notify new customers by e-mail, and choose Viewer underneath Direct roles and knowledge restrictions, then click on Add.
That completes the Google Analytics properties part. Your “software” will use the Google software credentials containing the client_email and can now have entry to your Google Analytics account through the Google Analytics Information API.
Slack Channels and Webhook
Within the following steps, you’ll create a brand new Slack channel that will probably be used to submit messages despatched out of your “software” utilizing a Slack Webhook.
Creating The Slack Channel
Create a brand new channel in your Slack workspace. I’ve named mine #weekly-analytics-report. You’ll have to set this up earlier than continuing to the following step.
Making a Slack App
Head over to the slack api dashboard, and click on Create an App.
On the following display screen, choose From an app manifest.
On the following display screen, choose your Slack workspace, then click on Subsequent.
On this display screen, you can provide your app a reputation. In my instance, I’ve named my Weekly Analytics Report. Click on Subsequent while you’re prepared.
On step 3, you may simply click on Achieved.
With the App created, now you can arrange a Webhook.
Making a Slack Webhook
Navigate to Incoming Webhooks from the left-hand navigation, then swap the Toggle to On to activate incoming webhooks. Then, on the backside of the display screen, click on Add New Webook to Workspace.
On the following display screen, choose your Slack workspace and a channel that you simply’d like to make use of to submit messages, too, and click on Enable.
It is best to now see your new Slack Webhook with a duplicate button. Copy the Webhook URL, and when you’ve already cloned the repo and adopted the Getting began steps within the README, add the Webhook URL to the SLACK_WEBHOOK_URL variable in your .env file.
Slack App Configuration
From the left-hand navigation, choose Fundamental Data. On this display screen, you may customise your app and add an icon and outline. Remember to click on Save Adjustments while you’re completed.
For those who now head over to your Slack, it is best to see that your app has been added to your workspace.
That completes the Slack part of this text. It’s now time so as to add your surroundings variables to GitHub Secrets and techniques and run the workflow.
Add GitHub Secrets and techniques
Head over to the Settings tab of your GitHub repository, then from the left-hand navigation, choose Secrets and techniques and variables, then click on Actions.
Add the three variables out of your .env file underneath Repository secrets and techniques.
A observe on the base64 string: You gained’t want to incorporate the double quotes!
Run Workflow
To check in case your Motion is working appropriately, head over to the Actions tab of your GitHub repository, choose the Job identify (Weekly Analytics Report), then click on Run workflow.
If the whole lot labored appropriately, it is best to now be a properly formatted record of the highest ten web page views in your web site in Slack.
Completed
And that’s it! A totally automated Google Analytics report that posts on to your Slack. I’ve labored in a number of locations the place Google Analytics knowledge was on lockdown, and I believe this method to sharing Analytics knowledge with Slack (one thing everybody has entry to) could possibly be tremendous useful for varied folks in your group.
Subscribe to MarketingSolution.
Receive web development discounts & web design tutorials.
Now! Lets GROW Together!