Logo
Published on
ยท4 min read

Adding Google Analytics to Next.js Blog

I apologize in advance for any awkward expressions in English. ๐Ÿ™

English is not my native language, and I have relied on ChatGPT's assistance to proceed with the translation.

Overview

In this guide, we'll show you how to connect Google Analytics to your blog to track traffic and gather valuable insights.

Prerequisites

  • I already have an existing Google Analytics account.
  • I've started my project with the Tailwind CSS Blog Starter template, which already includes Google Analytics code.

Create a Google Analytics property

  1. In Google Analytics, click Settings Admin (lower left).

    • Click on Account > Property > + Create Property
  2. Create a property

    • Property name (required): Specify a name you can recognize.
    • Reporting time zone: I specified South Korea.
    • Currency: I specified US Dollar ($).
  3. Describe your business

    • Industry category (required): Select the category that suits you.
    • Business size (required): Select the size that suits you.
  4. Choose your business objectives

    • Select the goal you want.
  5. Click on the Create button.

  6. Add a data stream

    • Select Web
    • Set up data stream: Enter the website URL. I entered hlog.kr (I also used the same name for the stream).
    • Click the Create stream button.
  7. You will see details for the web stream and installation instructions.

Connecting Google Analytics Code to the Source Code

The Tailwind CSS Blog Starter template already has this code implemented, and you only need to enter your Measurement ID (G-XXXXXXXXXX).

1. Connect Measurement ID with Code

  • In /data/siteMetadata.js, enter your Measurement ID (G-XXXXXXXXXX) into googleAnalyticsId.
const siteMetadata = {
  analytics: {
    googleAnalyticsId: 'Your Measurement ID', // e.g. UA-000000-2 or G-XXXXXXX
  },
}

That's it! You're now connected to Google Analytics.

2. Local Testing

You can skip local testing if you prefer. To skip it and proceed directly to the next step.

In the Tailwind CSS Blog Starter template code, Google Analytics code runs only in production mode. To make it work locally for testing purposes, you need to temporarily modify the code.

In the /components/analytics/index.js file, change isProduction to !isProduction like this:

{
  !isProduction && siteMetadata.analytics.googleAnalyticsId && <GA />
}

This change will allow you to test Google Analytics locally. However, remember to switch it back to isProduction when deploying your website.

You will see your tracking ID in the code when inspecting the developer tools. However, you might encounter the following error message in the developer console:

Refused to load the script 'https://www.googletagmanager.com/gtag/js?id=' because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval' 'unsafe-inline' giscus.app". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

Whether it's on the local environment or after deployment, the issue remains the same.
This is a Content Security Policy problem.

3. Modifying Content Security Policy

  1. Open the /next.config.js file.
  2. Content-Security-Policy Configuration: Choose one of the two methods.

Method 1. Add *.googletagmanager.com to script-src in the ContentSecurityPolicy configuration.

const ContentSecurityPolicy = `
  default-src 'self';
  script-src 'self' 'unsafe-eval' 'unsafe-inline' giscus.app *.googletagmanager.com;
  style-src 'self' 'unsafe-inline';
  img-src * blob: data:;
  media-src 'none';
  connect-src *;
  font-src 'self';
  frame-src giscus.app
`

Method 2. You can also pass an empty value to the Content-Security-Policy to disable this policy as follows:

const securityHeaders = [
  {
    key: 'Content-Security-Policy',
    value: '', //ContentSecurityPolicy.replace(/\n/g, ''),
  },
]

This part was not applied automatically with a refresh, so I had to restart (npm start) to apply it.

You can see that the error has disappeared.

4. Verify on Google Analytics

Access Google Analytics and select the Realtime menu to see real-time traffic being tracked.