Adding google analytics to a video in NuxtJS

Amarachi Iheanacho

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.

What we will be building

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

Prerequisities

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.

Setting up our Nuxtjs app

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.

1npm init nuxt-app <project-name>
2
3 #or
4
5 npx create-nuxt-app <project-name>
6
7 #or
8
9 yarn create nuxt-app <project-name>

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

1Project name: google-analytics-nuxt
1Programming language: JavaScript`
1Package manager: Npm
1UI framework: None
1Testing framework: None
1Rendering mode: Universal (SSR/SSG)
1Deployment target: Server (Node.js hosting)

After that, we run these commands

1cd <project name>
2
3 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/

Installing Cloudinary.

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.

1<!DOCTYPE html>
2 <html lang="en" {{ HTML_ATTRS }}>
3 <head {{ HEAD_ATTRS }}>
4 {{ HEAD }}
5 </head>
6 <body {{ BODY_ATTRS }}>
7 {{ APP }}
8 </body>
9 </html>

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

1<script src="https://unpkg.com/cloudinary-core@latest/cloudinary-core-shrinkwrap.min.js"></script>
2 <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

1<!DOCTYPE html>
2 <html lang="en" {{ HTML_ATTRS }}>
3 <head {{ HEAD_ATTRS }}>
4 {{ HEAD }}
5 <script src="https://unpkg.com/cloudinary-core@latest/cloudinary-core-shrinkwrap.min.js"></script>
6 <script src="https://unpkg.com/cloudinary-video-player@1.5.9/dist/cld-video-player.min.js"></script>
7 </head>
8 <body {{ BODY_ATTRS }}>
9 {{ APP }}
10 </body>
11 </html>

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

1touch .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.

1CLOUD_NAME = <Cloudinary-cloud-name>

Creating our Video Player

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 .

1<template>
2 <div>
3 <video
4 id= "video-player"
5 class="cld-video-player"
6 >
7 </video>
8 </div>
9 </template>

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

1// pages/index.vue
2
3 <script>
4
5 export default {
6 data(){
7 return{
8 cld: null,
9 player: null,
10 video: "production_ID_4456999_gr6iy4"
11 }
12 },
13 mounted(){
14 this.cld= cloudinary.Cloudinary.new({
15 cloud_name: process.env.CLOUD_NAME,
16 secure: true
17 })
18 this.player = this.cld.videoPlayer(
19 'video-player', {
20 controls: true
21 }
22 );
23 this.player.source(this.video);
24 }
25 }
26
27 </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.

1<style scoped>
2 div{
3 display: flex;
4 align-items: center;
5 justify-content: center;
6 }
7 .cld-video-player{
8 width: 500px;
9 height: 500px;
10 }
11 </style>

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

Specifying the video events to analyze

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

1mounted(){
2 this.cld= cloudinary.Cloudinary.new({
3 cloud_name: 'amarachi-2812',
4 secure: true
5 })
6 this.player = this.cld.videoPlayer(
7 'video-player', {
8 controls: true,
9 analytics: {
10 events: [
11 'play',
12 'pause',
13 'ended'
14 ]
15 }
16 }
17 );
18 this.player.source(this.video);
19 }

Linking our project to our Google analytics property

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

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

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

Our app.html file should look like this

1<!DOCTYPE html>
2 <html lang="en" {{ HTML_ATTRS }}>
3 <head {{ HEAD_ATTRS }}>
4
5 {{ HEAD }}
6 <script>
7 (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
8 (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
9 m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
10 })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
11
12 ga('create', 'UA-<our ID>', 'auto');
13 ga('send', 'pageview');
14 </script>
15
16 <script src="https://unpkg.com/cloudinary-core@latest/cloudinary-core-shrinkwrap.min.js"></script>
17 <script src="https://unpkg.com/cloudinary-video-player@1.5.9/dist/cld-video-player.min.js"></script>
18
19 </head>
20 <body {{ BODY_ATTRS }}>
21 {{ APP }}
22 </body>
23 </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.

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

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

Conclusion

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.

Resources

You may find these resources useful:

Amarachi Iheanacho

Frontend Engineer and Technical Writer