Quick Guide: Add Google Analytics to the Nuxt.js GitLab pages site
This will be a quick guide to add Google Analytics to our Nuxt.js App. This is mainly for non-developers who want to run their own personal site.
Checkout this tutorial to get the site up and running for free.
Add Google Analytics
First, let’s checkout a solution via Nuxt.js resources… this page took me to a Github page:
The Github page here:
Excellent! A Nuxt module for easy install. Let’s install the module via NPM.
$ npm install @nuxtjs/google-analytics --save
This will install locally and add to your package.json
. We can now add the GA Tracking ID. Go to Google Analytics and signup. Add the domain for your Nuxt.js app and proceed until you see the GA Tracking ID. It looks something like: `UA-XXXXXXXX`.
Now, open the nuxt.config.js
file from your project and add the GA module (in Bold):
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'Tim Skaggs - %s',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Code + Outside' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
/*
** Customize the progress bar color
*/
loading: { color: '#3B8070' },
/*
** Customize the generated output folder
*/
generate: {
dir: 'public'
},
/*
** Customize the base url
*/
router: {
base: '/'
},/*
** Build configuration
*/
build: {
/*
** Run ESLint on save
*/
extend (config, { isDev, isClient }) {
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
},/** ADD THIS **/
modules: [
// Simple usage
['@nuxtjs/google-analytics', {
id: process.env.GA_ID || ''
}]
]
}
We added a ENV Variable call GA_ID
. Why? Because we want to start protecting IDs.
Now we can test locally for errors by adding the ENV in your terminal like:
export GA_ID="UA-XXXXXX"
Start the server and make sure there are no errors.
Add the GA_ID Variable to Gitlab
Let’s add the GA_ID Variable to Gitlab for deployment. Open up Gitlab’s CI/CD settings:
And open the Variables tab and add a variable called “GA_ID” and add the full “UA-XXXXXX” ID from GA:
Now, add your changes and merge/push into the master
branch and the CI should automatically run. After that’s complete, open up your site in a separate browser and then log into your GA account and go to the Real-time tab and see your visitors!