How to add Google Analytics to the Modern SharePoint

Having an analytics tool monitoring your intranet is essential to understand the engagement of the users and how they are interacting with the content that is published.

Google Analytics is widely used in the internet, it provides a concise analysis with reports of everything that happens in your site as well as real time reports, mostly targeted for public sites it also works on SharePoint intranets.

Earlier this year I wrote an article that explains step by step how to add Google Analytics to SharePoint without modifying the master page, while that solution is still valid for classic SharePoint it doesn’t work on the modern sites and libraries.

SPFx Google Analytics

In this article, I explain step by step how to build and deploy an Application Customizer using the SharePoint Framework Extensions, I am also providing the installation files and the instructions to use it if you don’t want to build it yourself.

How to setup Google Analytics

First things first, before we get into the SharePoint bits let’s set up google analytics and get everything you need.

  1. Sign in to your Analytics account
  2. Select the Admin tab
  3. Select an account from the menu in the ACCOUNT column, or CREATE NEW ACCOUNT if you don’t have one already
  4. Select a property from the menu in the PROPERTY column
  5. Under PROPERTY, click Tracking Info Tracking Code
  6. Save the Tracking Id
    Save Google Analytics tracking id

More information about google analytics setup can be found here.

Create the Application Customizer Extension project

The Application Customizer is one of the available extension types provided by the SharePoint Framework and allows you to add custom JavaScript to every page in a site or web.

To achieve the steps below you need to have installed the SPFx v1.4 or higher, you can get the latest version from here.

  1. Create a folder with the name of the project e.g. analytics
  2. Open the console window in the new directory
  3. Type the command yo @microsoft/sharepoint
  4. When prompted:
    • Accept the default app-extension as your solution name, and press Enter.
    • Choose SharePoint Online only (latest), and press Enter.
    • Choose Use the current folder, and press Enter.
    • Choose Y to make the extension available to be added without activating any features.
    • Choose Extension as the client-side component type to be created.
    • Choose Application Customizer as the extension type to be created.
    • Provide a name to the extension. e.g. analytics
    • Provide a description to the extension. e.g. Google Analytics for SharePoint modern pages
    • SPFx Extention Project

  5. The download of all the requirements might take a few minutes, once it’s done you will see a message indicating the success of the operation.

Build the extension

Now that you have the extension project created let’s proceed and modify it to include the Google Analytics JavaScript code.

  1. Type code . to open the project (this will open visual studio code but you can use another editor).
  2. On your solution go to src/extensions/analytics and open the AnalyticsApplicationCustomizer.ts
  3. Locate the interface it IAnalyticsApplicationCustomizerProperties and replace it by the code below
    export interface IAnalyticsApplicationCustomizerProperties {
     trackingID: string;
    }
    
  4. Locate the OnInit method and replace it by the code below
    public onInit(): Promise<void> {    
    	let trackingID: string = this.properties.trackingID;
    	if (!trackingID) {
    		Log.info(LOG_SOURCE, "Tracking ID not provided";);
    	}else{
    		var gtagScript = document.createElement("script");
    		gtagScript.type = "text/javascript";
    		gtagScript.src = `https://www.googletagmanager.com/gtag/js?id=${trackingID}`;    
    		gtagScript.async = true;
    		document.head.appendChild(gtagScript);  
    
    		eval(`
    			window.dataLayer = window.dataLayer || [];
    			function gtag(){dataLayer.push(arguments);}
    			gtag('js', new Date());    
    			gtag('config',  '${trackingID}');
    		`);
    	}
    	return Promise.resolve();
    }
    

    This snippet is a modified version of the code provided by Google, it was converted from JavaScript to TypeScript to use the Tracking Id dynamically.

Package the analytics solution

To deploy the analytics solution to all the users it needs to be packaged and installed in the SharePoint Online.

The instructions below are specific for SPFx 1.4 or higher and will make use of the Asset Packaging functionality.

  1. On your project go to the config folder and open the package-solution.json and confirm if the property includeClientSideAssets exists in the solution, if it doesn’t exist it means that you are not using SPFx 1.4 to update your project follow the steps described in this article.
    SPFx Extention Project
  2. To get the basic structure for the packaging run the command gulp bundle --ship
  3. To get the installation package run the command gulp package-solution --ship
  4. On your project structure navigate to sharepoint/solution, in this folder you will find the *.sppkg file

Install Google Analytics on Modern SharePoint

Extensions won’t be automatically enabled. SharePoint Framework extensions must be specifically associated to sites, lists, and fields programmatically to be visible to site users.

To achieve the steps described in this section you will need to install the SharePoint PnP PowerShell.

  1. If you haven’t built the project download the solution package from here
  2. Open your App Catalog and upload the sppkg file
  3. Check the box Make this solution available to all sites in the organization
    SPFx Extention Project
  4. On your project go to src/extensions/analytics and open the AnalyticsApplicationCustomizer.manifest.json
  5. Copy the id value
  6. Open the PowerShell command line
  7. To establish a connection, execute the command Connect-PnPOnline -UseWebLogin -Url https://yourtenant.sharepoint.com/
  8. To enable the extension, execute the command Add-PnPCustomAction -ClientSideComponentId "id" -Name "Analytics" -Title "Analytics" -Location ClientSideExtension.ApplicationCustomizer -ClientSideComponentProperties: '{"trackingID":"UA-00000000-1"}' -Scope site
    Replace the “id” by the client component id
    Replace the “UA-00000000-1” by your own google analytics tracking id
    SPFx Extention Project

Conclusion

In this article, you learned how to add Google Analytics to the Modern SharePoint sites and how to create an application customizer step by step.

If you were already using Google Analytics to monitor the SharePoint usage now you can combine your existent solution with this approach to get a complete overview of all the pages.

Download Google Analytics SPPKG V2
Explore Solution on GitHub

Designed by Freepik


46 Responses to “How to add Google Analytics to the Modern SharePoint”

  1. Dave

    December 22, 2017

    How do we do the same for SharePoint Online?

    Reply
    • João Ferreira

      December 22, 2017

      Hi Dave,

      The steps described in this article are for SharePoint Online modern team sites, lists and libraries.

      Reply
  2. Bart

    December 23, 2017

    Thank you for this nice example.

    fyi, line 4 in OnInit contains an unnecessary “;”

    Reply
    • João Ferreira

      December 23, 2017

      Thanks Bart, I’ll update the code.

      Reply
      • Bart

        December 23, 2017

        Cheers!
        It should surface in the “Add an app” in the Site contents, right? What can I check if it isn’t?

        Reply
        • João Ferreira

          December 23, 2017

          It is added automatically if you have checked Make this solution available to all sites in the organization. You just need to activate it using powershell

          Reply
          • Bart

            December 23, 2017

            I tried it without luck. Should the GUID in AnalyticsApplicationCustomizer.manifest.json be the same as the product-id in the app catalog? (It isn’t.)

          • João Ferreira

            December 23, 2017

            Not sure if it’s the same. Have you checked the box to make it available? It’s mandatory to get the extention running. Have you tested the code with a site collection workbench?

  3. João Miguel

    December 29, 2017

    Hi,

    Nice job. But it needs some more tuning.
    The events when switching between modern pages are not being count. Probably because that pages don’t make a full post back.

    Does the pnp command activates to all the sites and site collections on the tenant?
    I had to connect to another site collection and activate the extension. And the sites inside that site collection are not counting also. Am I missing something?

    Reply
    • João Ferreira

      December 29, 2017

      Hi João,

      Thanks for the feedback, the google post is only made on the first load of the page. I’ll work on a new version to register all the pages.
      Once you activate the extension it is added to the entire site collection. There is a know bug with application customizers where the extension is not loaded in some cases. More info here https://github.com/SharePoint/sp-dev-docs/issues/1042
      I’ll try to provide a more robust solution in the next version.

      Reply
      • João Miguel

        December 30, 2017

        Thanks,

        I’ll try to figure out that also.
        Probably one event will do the trick.

        But not this year…

        Happy new year

        Reply
      • Tuomas Pakkanen

        September 11, 2018

        Hi,

        Have you had a chance to update the code so that it would also track when user navigates between different pages on the modern site? Now it tracks only the first load, maybe a bit depending which navigation element is clicked.

        Best regards
        Tuomas

        Reply
        • João Ferreira

          October 10, 2018

          Hi Tuomas,

          I’m getting the solution updated and released this month, I was able to detect the changes when the navigation is made without redirects.

          Reply
          • Tuomas Pakkanen

            October 11, 2018

            Hi,

            Awesome job, thanks!

            Best regards
            Tuomas

          • Tuomas Pakkanen

            November 1, 2018

            No pressure, but have you had a chance to update this? Thanks a lot! Also curious about if you’ve done anything similar for Azure Application Insights?

          • João Ferreira

            November 10, 2018

            Hi Tuomas,

            The solution was updated and a version 2 is available for download.
            To get it up and running on your environment replace the existent sppkg file on the app catalog by the new one and don’t forget to deploy it globally.

            My best,

            João Ferreira

          • Tuomas Pakkanen

            November 12, 2018

            Hi,

            Thanks a lot, it works great!

            Best regards
            Tuomas

  4. Iro

    April 17, 2018

    Hello,

    Does this work for Office Groups as well? I tried to follow all your steps but it doesn’t seem to appear in the site contents after executing the scripts.

    Reply
    • João Ferreira

      April 17, 2018

      Hi Iro,

      This solution is compatible with group sites, it works for all modern SharePoint sites.
      When installing the solution make sure you check the option Make this solution available to all sites in the organization, with this option selected the solution will not appear in the site contents and is deployed globally to the site collection after executing the commands describes on step 8 and 9.
      Let me know if you were able to install the solution in your site.

      Reply
      • Iro

        May 25, 2018

        I was not able to install it, but I mistakenly thought it was a site of an Office Group while it was a communication site instead. So maybe the type of site has something to do with it?

        Reply
        • João Ferreira

          May 28, 2018

          Hi Iro,

          The type of site should not be a problem as long as you choose a modern site.

          My best,

          João Ferreira

          Reply
  5. Ihsan Rehman

    May 25, 2018

    one of the best examples of SPFX it actually explains how to start the journey, well done. hats off to you.

    Reply
  6. JP Nelson

    May 31, 2018

    Great post and I went thru it 3 times on 2 different tenants. I do not see the ext/app when I try to add it to a site. Does it take a while to show up? Or did I miss something?

    Reply
    • João Ferreira

      May 31, 2018

      Hi JP,

      Please make sure you check the box to make the solution available to all sites in the organization, as shown in the image bellow.
      SPFx Extention Project

      If you are using the package from the article make sure you add the extension with this GUID – 9811e000-540c-479c-8436-1cb4c4fd0484
      To intall the solution you should run the code bellow with your own tracking id.

      Connect-PnPOnline -UseWebLogin -Url https://yourtenant.sharepoint.com/
      Add-PnPCustomAction -ClientSideComponentId "9811e000-540c-479c-8436-1cb4c4fd0484" -Name "Analytics" -Title "Analytics" -Location ClientSideExtension.ApplicationCustomizer -ClientSideComponentProperties: '{"trackingID":"UA-00000000-1"}' -Scope site
      

      To check if the solution is being applied to the site collection use the code bellow. It will list all the extensions deployed at site collection level.

      Connect-PnPOnline -UseWebLogin -Url https://yourtenant.sharepoint.com/
      Get-PnPCustomAction -Scope site
      

      Hope this helps you to get the solution running.

      Reply
  7. Ellen Kong

    July 30, 2018

    How would we add Application Insights to SharePoint Online? We use both Google Analytics and Application Insights, but we a transitioning from Classic to Modern sites. Would we be able to use your solution and add in some extra lines for Application Insights? Or does that need to be a separate Application Customizer solution?

    Reply
    • João Ferreira

      July 31, 2018

      HI Ellen,

      It needs to be a separated Application Customizer,this is something I have on my back log for quite some time. It will be the next project I’ll release both for modern and classic SharePoint.

      Reply
  8. ihsan

    September 20, 2018

    solution doesn’t work with google tag manager as i can not see the logged categories inside GA. any ideas why??

    Reply
    • João Ferreira

      October 10, 2018

      Tag manager is not supported by this solution it will be available in this blog this year as a separate solution.

      Regards,

      Joao Ferreira

      Reply
  9. Aadil Ganie

    September 24, 2018

    Hi João,
    Thank you kindly for such a great post. One questions I do have..
    When packaging the solution using: gulp package-solution –ship
    it gives and error:
    The build failed because a task wrote output to stderr.
    Exiting with exit code: 1

    The package still gets built and still seems to work though. Though it may be something that could be of use..

    Reply
    • João Ferreira

      October 10, 2018

      Hi Aadil,

      Can you please let me know what version of the framework are you using to build the solution?

      Regards,

      João Ferreira

      Reply
  10. Nick Pettijohn

    October 8, 2018

    Hi, João.

    Thank you! Your instructions ran perfectly, the first time (after I removed the redundant semi-colon).

    I ran Get-PnPCustomAction -Scope site and see “Analytics” listed. Now what?

    1. How do I know which site collections are using this Application Customizer?
    2. What activation steps do I need to take at the site collection and/or site level, if any?
    3. How do I use/activate this on a classic site that has some modern pages on it?

    Thank you again!

    Nick

    Reply
    • João Ferreira

      October 10, 2018

      Hi Nick,

      Thanks for your comment I appreciate your feedback.

      1 – The application customizer is only used by modern site and pages where you deployed the extension, for each site collection where you want to monitor modern site you will need to execute step 7 and 8 using PowerShell

      2 – Once you do it at site collection level it will work on all modern sites and pages in the site collection

      3 – To use Google analytics you will need to use another solution that I also built, and it’s available in the link bellow, both can be used on the same site collection if you are using modern and classic site together.

      http://sharepoint.handsontek.net/2017/02/26/how-to-add-google-analytics-to-sharepoint-without-modifying-the-master-page/

      Reply
  11. Nick Pettijohn

    October 10, 2018

    I found my issue: Double-checked package-solution.json in the Config folder. Changed “skipFeatureDeployment” from “true” to “false”. Re-packaged and uploaded to the AppCatalog. I can now add the app to any site collection or site.

    Questions:
    1. Is activating at the top of a site collection sufficient, or does each sub-site need it added?
    2. How does this work on a classic site collection with a mixture of wiki pages and classic pages? Would I need to install the classic solution also? Or one or the other, but not both?

    Nick

    Reply
    • Nick Pettijohn

      October 10, 2018

      Edit:
      2. How does this work on a classic site collection with a mixture of wiki pages and MODERN pages? Would I need to install the classic solution also? Or one or the other, but not both?

      Reply
      • João Ferreira

        October 10, 2018

        You need to use both solutions, the modern one will be loaded only on modern pages and the same thing happens for the classic solution.

        Reply
        • Jiri F.

          November 23, 2018

          Hi,
          I’ve added the GA to our SharePoint tenant and I can see in source code of the modern SP pages the string “customActions” : [{“title”:”Analytics”,”location”:”ClientSideExtension.ApplicationCustomizer”,”clientSideComponentId” … ” with my Google Analytics trackingID in it, but there are no data measured in Google analytics for these pages.
          Is there anything else what needs to be done, to make it work?

          And I’d like to ask if the GA is supposed to also apear on Modern SharePoint websites created as part of Office 365 Groups / Microsoft Teams, because I can’t see the GA trackingID in the source code of pages on these sites.

          Thanks,

          Jiri

          Reply
          • João Ferreira

            November 25, 2018

            Hi Jiri,

            Sometimes when you with open sessions on SharePoint and Google Analytics in the same browser the tracking doesn’t work.
            If you can’t see the data from other users on other computers, please make sure the Analytics ID is correct.
            This solution will work on all modern sites you just need to enable the extension on all sites that you want to track.

            Thanks,

            João

    • João Ferreira

      October 10, 2018

      Thanks for the feedback Nick, this is not the desired behavior but I’m glad you were able no make it work using this trick.

      1 – Activation at the top of the site collection is sufficient, however with the latest updates on modern when navigating between pages you might not get the new page into the analytics. I’m working on a solution to solve this issue that I’ll publish this month.

      2 – You need to install both solutions for scenarios like this

      Reply
  12. Rami

    October 10, 2018

    Hi Joao,

    I have faced the issue with:

    “Add-PnPCustomAction : A parameter cannot be found that matches parameter name ‘ClientSideComponentId’.”

    I have tried both created own .sppkg file and your pkg with,
    Add-PnPCustomAction -ClientSideComponentId “9811e000-540c-479c-8436-1cb4c4fd0484” -Name “Analytics” -Title “Analytics” -Location ClientSideExtension.ApplicationCustomizer -ClientSideComponentProperties: ‘{“trackingID”:”UA-my-own-id”}’ -Scope site.

    Please give me a suggestion.

    Thanks and Regards,

    Rami

    Reply
    • João Ferreira

      October 10, 2018

      Hi Rami,

      In order to execute this command you need to have the PNP powershell installed looking to your command it seems to be correct.
      I did a double check on Microsoft documentation https://docs.microsoft.com/en-us/powershell/module/sharepoint-pnp/add-pnpcustomaction?view=sharepoint-ps
      Please make sure you have the PnP cmdlets installed

      Regards,

      Joao Ferreira

      Reply
      • Rami

        October 11, 2018

        HI Joåo,

        I have installed SharePointPnPPowerShell2016 and checked the PnP cmdlets. Want me to install SharePointPnPPowerShellOnline and excute this command?!.

        Thanks,

        Rami

        Reply
        • João Ferreira

          November 25, 2018

          Hi Rami,

          To use this solution you will need to use the SharePointPnPPowerShellOnline

          Thanks,

          João

          Reply
  13. Jason Brownhill

    November 23, 2018

    Hi Joao,
    In the newly revised version I think you’re referencing a property in the file ‘AnalyticsApplicationCustomizer.ts’ that is missing if I just take the one page from your github revision? This is the point it isn’t happy with in the code on that page:

    ${strings.MissingID}`);

    I just removed the .MissingID and recompiled, everything built okay. Just testing now.

    Hope that helps.
    Jason.

    Reply
    • João Ferreira

      November 25, 2018

      Hi Jason,

      Thanks for letting me know, I’ll validate the code to check what happened to the strings file.

      Thanks,

      João

      Reply

Leave a Reply


Web developer focused on SharePoint branding, blogger, tech enthusiast. Travelling and sports are my addictions, knowledge and success are my daily motivations.