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 =;
    	if (!trackingID) {, "Tracking ID not provided";);
    		var gtagScript = document.createElement("script");
    		gtagScript.type = "text/javascript";
    		gtagScript.src = `${trackingID}`;    
    		gtagScript.async = true;
    			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
  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


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
Explore Solution on GitHub

Designed by Freepik

22 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?

    • João Ferreira

      December 22, 2017

      Hi Dave,

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

  2. Bart

    December 23, 2017

    Thank you for this nice example.

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

    • João Ferreira

      December 23, 2017

      Thanks Bart, I’ll update the code.

      • Bart

        December 23, 2017

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

        • 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

          • 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


    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?

    • 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
      I’ll try to provide a more robust solution in the next version.

      • João Miguel

        December 30, 2017


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

        But not this year…

        Happy new year

  4. Iro

    April 17, 2018


    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.

    • 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.

      • 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?

        • 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

  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.

  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?

    • 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
      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
      Get-PnPCustomAction -Scope site

      Hope this helps you to get the solution running.

  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?

    • 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.


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.