Skip to content

Adding google analytics to a video in NuxtJS

User insights are among the most powerful tools we can use to grow our business website and, by extension, our business. They allow us to understand our audience, their demographics, and more importantly, what they expect from our website.

This post will discuss how to use the Cloudinary video player to track and report video events and analytics to Google analytics. These events include start, pause, play, finish.

At the end of this tutorial, we will learn how to use Cloudinary and Google analytics to collect user insights on our application.

The completed project is on Codesandbox. Check out the Codesandbox to get started quickly.

Github URL:

https://github.com/Iheanacho-ai/google-analytics-nuxt

To get the most out of this article, we require the following:

  • A basic understanding of CSS, JavaScript and Vue.js
  • Understanding Nuxt.js would help us follow this tutorial quicker, but it is not entirely required.
  • A Cloudinary account, you can create one here.

Nuxt.js is an open-source vue.js frontend development framework that allows us to create universal web applications without stress, render statically Vue.js applications without having a server, and enables functionalities like server-side rendering, static site generating, etc. in our project.

To create a nuxt.js app, we go to our terminal and run the command below.

NOTE: If you are on windows and using Git Bash you might have issues with the arrows, so you should use the Powershell terminal instead.

  npm init nuxt-app <project-name>
   
   #or
   
   npx create-nuxt-app <project-name>
   
   #or
   
   yarn create nuxt-app <project-name>

Running this command will trigger a set of question prompts. Here is the setup I used.

Project name: google-analytics-nuxt

Programming language: JavaScript`
    Package manager: Npm

    UI framework: None

    Testing framework: None

    Rendering mode: Universal (SSR/SSG) 

    Deployment target: Server (Node.js hosting)

After that, we run these commands

    cd <project name>
    
    npm run dev

This would change the directory to our project and run it on the browser, to see our app go to http://localhost:3000/

Nuxtjs starter app

Cloudinary is a cloud-based service that provides an end-to-end image and video management solution, including uploads, storage, manipulations, optimizations, and delivery.

It also allows developers to embed video players in their app that handles video events effectively.

To enable our nuxt app to use these Cloudinary features, in our project’s root directory, we create an app.html file with the following content.


    <!DOCTYPE html>
    <html lang="en" {{ HTML_ATTRS }}>
      <head {{ HEAD_ATTRS }}>
        {{ HEAD }}
      </head>
      <body {{ BODY_ATTRS }}>
        {{ APP }}
      </body>
    </html>

Underneath {{Head}} paste these Cloudinary script tags.


     <script src="https://unpkg.com/cloudinary-core@latest/cloudinary-core-shrinkwrap.min.js"></script>
      <script src="https://unpkg.com/cloudinary-video-player@1.5.9/dist/cld-video-player.min.js"></script> 

Our app.html file should look like this

    <!DOCTYPE html>
    <html lang="en" {{ HTML_ATTRS }}>
      <head {{ HEAD_ATTRS }}>
        {{ HEAD }}
         <script src="https://unpkg.com/cloudinary-core@latest/cloudinary-core-shrinkwrap.min.js"></script>
          <script src="https://unpkg.com/cloudinary-video-player@1.5.9/dist/cld-video-player.min.js"></script> 
      </head>
      <body {{ BODY_ATTRS }}>
        {{ APP }}
      </body>
    </html>

Next up, we create a .env file at the root of our project.

    touch .env

After creating our .env file, we go to our Dashboard. In the Account Details section, we can see our cloud name. We copy and paste it in our .env file.


    CLOUD_NAME = <Cloudinary-cloud-name>

In our index.vue file, we embed the Cloudinary video player in our project using the HTML5 native video element. We then give the element an id of video-player and a class of cld-video-player .

    <template>
      <div>
        <video 
        id= "video-player"
        class="cld-video-player"
        >
        </video> 
      </div>
    </template>

In our mounted lifecycle hook, we create a Cloudinary instance once the page loads.

    // pages/index.vue
    
    <script>
    
    export default {
      data(){
        return{
          cld: null,
          player: null,
          video: "production_ID_4456999_gr6iy4"
        }
      },
      mounted(){
        this.cld= cloudinary.Cloudinary.new({
          cloud_name:  process.env.CLOUD_NAME,
          secure:  true
        })
        this.player = this.cld.videoPlayer(
          'video-player', {
                controls: true
            }
        );
        this.player.source(this.video);
      }
    }
    
    </script>

In the data object, we define four variables to start with:

  • The cld variable holds the Cloudinary instance we will create.
  • The player variable has the new Cloudinary video player we will instantiate on mount.
  • The video variable holds the video’s id we are looking to play. This video is stored on Cloudinary.
  • The controls variable controls the native player controls.

In our mounted lifecycle hook, we create a Cloudinary instance from the Cloudinary object by passing into it as an argument the cloud name we stored in our .env file and secure: true.

We then instantiate the Cloudinary video player by using the videoPlayer method and passing in two arguments:

  • The video player’s id or the video player element itself.
  • An object which sets the controls on the video to true.

Next, we add the Cloudinary video public ID stored in our video variable as the source for the player.

In the style section of our index.vue file, we add a bit of styling to our video player, we center the div containing our video player with the native CSS flex property, we then give our video player a width of 500px and a height of 500px.

    <style scoped>
     div{
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .cld-video-player{
      width: 500px;
      height: 500px;
    }
    </style>
    

With that we have embedded a Cloudinary video player in our project.

Cloudinary Video Player

We want to know how many users played, paused or watched our video to the end. To do this, we use the Cloudinary analytics parameter.

In our index.vue file, we go to our mounted lifecycle method and pass in our analytics object. In this object, we define an events array which contains the list of events we want to listen to (play, pause, ended).

     mounted(){
        this.cld= cloudinary.Cloudinary.new({
          cloud_name:  'amarachi-2812',
          secure:  true
        })
        this.player = this.cld.videoPlayer(
          'video-player', {
            controls: true,
            analytics: {
              events: [
                'play',
                'pause',
                'ended'
              ]
            }
          }
        );
        this.player.source(this.video);
    }


Hosting our application

To get started with this section of the article, we must host our application. Netlify is an excellent option.

Netlify is a cloud computing-based company that offers hosting and serverless backend services for web applications and static websites. It is straightforward to use, fast and automatically enables continuous deployment for projects deployed from Git repos.

Check out this piece here to learn how to host your website on Netlify.

Creating a Google Analytics account

Getting a report from Google Analytics on our application is important to create a Google Analytics account. Create a free account here.

Creating a property

After creating an account, the next thing we want to do is to create a property on our account. We can understand the property to be a Google analytics project. To learn how to create a property, check out this article here.

Note: When creating our property, it is important to navigate to the “Hide advanced options” section at the bottom of the page and agree to “Create a Universal Analytics property”.

Google Analytics UA

Google Analytics then creates two types of properties with the name we provided.

  • A Google Analytics 4 property
  • A Universal Analytics property.

We will use the Universal Analytics property. Go to the top of the website, click the dropdown select the property with the property name we just created and an ID with the UA prefix (this stands for Universal Analytics).

Google Analytics UA ID

We copy this ID as we will need it in our project.

Adding the Google analytics tag in our project

In our app.html, we paste this code just above the cloudinary source scripts and input our ID from earlier

     <script>
            (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
            })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
            // our ID goes in here
            ga('create', 'UA-<our ID>', 'auto');
            ga('send', 'pageview');
    </script>
    

Our app.html file should look like this

    <!DOCTYPE html>
    <html lang="en" {{ HTML_ATTRS }}>
     <head {{ HEAD_ATTRS }}>
        
        {{ HEAD }}
          <script>
            (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
            })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
            
            ga('create', 'UA-<our ID>', 'auto');
            ga('send', 'pageview');
          </script>
    
      <script src="https://unpkg.com/cloudinary-core@latest/cloudinary-core-shrinkwrap.min.js"></script>
      <script src="https://unpkg.com/cloudinary-video-player@1.5.9/dist/cld-video-player.min.js"></script>
    
      </head>
      <body {{ BODY_ATTRS }}>
        {{ APP }}
      </body>
    </html>

With this we have successfully added google analytics in our project. To test this out, go to the Google Analytics sidebar on the left and choose “Home” to find how many users have engaged with our site and triggered those events over a specific period.

Google Analytics Home Dashboard

The “Real Time” Tab on the sidebar tells us how many users have used our application in the last 30 minutes.

Google Analytics Home Dashboard

At the bottom, we can see that the user fired off the play video event

This article discussed integrating Google analytics into our project to track how many users interact with our application, their actions, and what video player events they fired.

You may find these resources useful:

Back to top

Featured Post