One of the recurrent requirements most business keep asking about, is how can I track the usage of my intranet, or sharepoint portals ?
SharePoint Online (or On-Prem) provides a certain level of analytics, but, unless you are using a third party tools, the SharePoint Analytics are very basic and provide limited information.
In this article, I will describe, how you can integrate your SharePoint sites with Google Analytics, and take advantage of the advanced metrics and dashboard available in Google Analytics.
To achieve this, we will need to build a site extension using SPFx and deploy it to your tenant App Catalogue.
First, you will need to set up your SPFx development environment, if you have not already completed this step, please refer to my previous article
1- Create a project folder
This step is optional, I will create a new folder in my desktop (did not want to overthink this), to host my project file.
2- Using Yeoman Generate, create a new project
Second, using the Yoman Generator, we will scaffold a new SPFx project.
I will call “yo” first, and select “@microsoft/sharepoint” scaffolding template.
3- Define the project type and details
This step is very important, you will need to make sure that you are:
- Selecting “Extension” as the type of client-side component,
- and, “Application Customizer” as the type of client-side extension.
I will call my solution SPGA (SharePoint-GoogleAnalytics).
4- The magic !
At this stage, you have an brand new SPFx project for an Application Customizer Extension.
You can type “code .” to open the project folder in VS Code, or you can just open the solution in your preferred IDE.
Include the Google Analytics Script
Assuming, you have already created your entity in Google Analytics and pulled the integration script (which we might not need at this stage).
The next step, is to navigate to
“src/extensions/SharepointGoogleAnalyticsIntegrationApplicationCustomizer.ts” file, and locate the “onInit” function
The reason, I said earlier, we might not need the script generated from Google Analytics, is because, we need to translate the JS code given by Google Analytics to TypeScript instead.
All we need at this stage if the tracking ID
Now, replace the “onInit” function’s code by the following:
That’s is! you’re almost done.
5- Package and deploy your solution
Final stage of the process, package and deploy your newly created solution.
5.1 Package the solution
Back to your preferred terminal,
Run the following command to bundle the project
Next, we need to package the solution to generate the final .sppkg file.
5.2 Deploy the solution
Once you have packaged your solution, a new .sppkg file will be created under “sharepoint/solution” folder.
You will need to import the .sppkg file to your SharePoint App catalogue and add the newly created app to your site.
Open source code
The entire code of the solution is available from my GitHub –> https://github.com/samirlogisam/spga