Track page hits with SharePoint Framework and App Insights
A need for modern SharePoint site page hits or analytics
Page hits are maybe one of the first business requirements we get from the business when we start on a new project. Also typical for News and publishing SharePoint portals to identify how many times an article has been visited for example. The SharePoint basic 'Site usage' page (/_layouts/15/siteanalytics.aspx?view=11) does not offer hits per page now, so we can use application insights to track that until that has been implemented.
Is application insights a good fit?
Track page hits with a hidden application customizer
I also assume that you have SharePoint Framework development environment setup and new application customizer is scaffold-ed using the Yeoman generator so we can focus on the actual app insights implementation.
Add app insights reference to the package.json
Run npm install to get the new packages
Able to configure application insights without the need to redeploy the SharePoint solution package
When creating the app customizer we can add the app insights instrumentation key as property of the app customizer so we can change it at any given time by just running office365 cli or PnP PowerShell script. So our application property can look like that:
Then we can import the application insights into our customizer and set it to send page hits. Here is how the entire code might look like:
Custom data payload when page hit request is send
We can use the SharePoint Framewrok component context as quick reference to information if we have to pass some additional details along with the page hits. As can be seen from the code above, I am sending user display name, absolute url and other details from the context of the application customizer. This is handy and does not cost additional requests, but the payload can be any type of data. For example you might like to access the user profiles service and pass more details for the current user or access a list and pass data from that list.
Change the app insights instrumentation key
Since we added the instrumentation key as property, we can easily change it without the need to redeploy the Application Customizer solution package. We just need to know the user custom action id that the customizer has been deployed with.
The office 365 cli tool has handy command for updating the instrumentation key:
PnP Powershell cmdlet is also available :
This is maybe 30 mins setup, but can give the business valuable information on the usage of the modern SharePoint pages and it is flexible enough so the key can be changed without the need to redeploy the solution.