Skip to content

Google Analytics Setup Guide

This guide provides detailed instructions on how to integrate Google Analytics into your MkDocs Material site for access analysis.

Prerequisites

1. Google Analytics 4 (GA4) Setup

1.1 Creating a Google Analytics Account

  1. Access Google Analytics
  2. Click "Start measuring"
  3. Enter an account name (e.g., My Documentation Site)
  4. Review account settings
  5. Click "Next"

1.2 Property Setup

  1. Enter a property name (e.g., MkDocs Site)
  2. Set reporting time zone to "Japan"
  3. Set currency to "Japanese Yen"
  4. Click "Next"

1.3 Business Details

  1. Select an industry category (e.g., "Computers & Electronics")
  2. Select business size
  3. Click "Create"

1.4 Data Stream Setup

  1. Select "Web"
  2. Enter your website URL
    https://username.github.io/repository-name/
    
  3. Enter a stream name (e.g., GitHub Pages Site)
  4. Click "Create stream"

1.5 Obtaining the Measurement ID

After creation is complete, copy the Measurement ID (in the format G-XXXXXXXXXX).

GA4 Measurement ID Example

2. Implementation in MkDocs

Add Google Analytics configuration to mkdocs.yml:

# Google Analytics 4
plugins:
  - search:
      lang: en

# Analytics (recommended method)
extra:
  analytics:
    provider: google
    property: G-XXXXXXXXXX  # Replace with your measurement ID
    feedback:
      title: Was this page helpful?
      ratings:
        - icon: material/emoticon-happy-outline
          name: This page was helpful
          data: 1
          note: >-
            Thanks for your feedback!
        - icon: material/emoticon-sad-outline
          name: This page could be improved
          data: 0
          note: >-
            Thanks for your feedback! We'll work on improving it.

2.2 Legacy Setup (Deprecated but Usable)

If you have an older Universal Analytics (UA) property:

# Universal Analytics (legacy)
google_analytics:
  - 'UA-XXXXXXXX-X'
  - 'auto'

Universal Analytics Discontinued

Universal Analytics was discontinued on July 1, 2023. Use GA4 for new implementations.

3. Custom Event Setup

3.1 Adding Event Configuration

Set up custom events for more detailed analysis:

extra:
  analytics:
    provider: google
    property: G-XXXXXXXXXX
    feedback:
      title: Was this page helpful?
      ratings:
        - icon: material/thumb-up-outline
          name: Yes
          data: 1
          note: Thank you!
        - icon: material/thumb-down-outline
          name: No
          data: 0
          note: We'll work on improving it.

3.2 Extension with Custom JavaScript

Create docs/javascripts/analytics.js:

// Custom event tracking
document.addEventListener('DOMContentLoaded', function() {
  // Track external link clicks
  document.querySelectorAll('a[href^="http"]').forEach(function(link) {
    link.addEventListener('click', function() {
      gtag('event', 'click', {
        event_category: 'external_link',
        event_label: this.href,
        transport_type: 'beacon'
      });
    });
  });

  // Track download links
  document.querySelectorAll('a[href$=".pdf"], a[href$=".zip"], a[href$=".doc"]').forEach(function(link) {
    link.addEventListener('click', function() {
      gtag('event', 'download', {
        event_category: 'file_download',
        event_label: this.href.split('/').pop(),
        transport_type: 'beacon'
      });
    });
  });

  // Track search
  const searchInput = document.querySelector('[data-md-component="search-query"]');
  if (searchInput) {
    searchInput.addEventListener('input', function() {
      if (this.value.length > 2) {
        gtag('event', 'search', {
          search_term: this.value
        });
      }
    });
  }
});

// Track scroll depth
let scrollDepth = 0;
window.addEventListener('scroll', function() {
  const currentScroll = Math.round((window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100);

  if (currentScroll > scrollDepth && currentScroll % 25 === 0) {
    scrollDepth = currentScroll;
    gtag('event', 'scroll', {
      event_category: 'engagement',
      event_label: scrollDepth + '%',
      value: scrollDepth
    });
  }
});

Add the JavaScript file to mkdocs.yml:

extra_javascript:
  - javascripts/analytics.js

4. Privacy Settings

Create docs/javascripts/cookie-consent.js:

// Display cookie consent banner
function showCookieConsent() {
  const consent = localStorage.getItem('cookie-consent');

  if (!consent) {
    const banner = document.createElement('div');
    banner.innerHTML = `
      <div style="position: fixed; bottom: 0; left: 0; right: 0; background: #333; color: white; padding: 1rem; z-index: 9999;">
        <p style="margin: 0 0 1rem 0;">
          This site uses Google Analytics to improve user experience.
          <a href="/privacy/" style="color: #4FC3F7;">Privacy Policy</a>
        </p>
        <button id="accept-cookies" style="background: #4FC3F7; color: white; border: none; padding: 0.5rem 1rem; border-radius: 4px; margin-right: 1rem;">Accept</button>
        <button id="decline-cookies" style="background: #666; color: white; border: none; padding: 0.5rem 1rem; border-radius: 4px;">Decline</button>
      </div>
    `;

    document.body.appendChild(banner);

    document.getElementById('accept-cookies').addEventListener('click', function() {
      localStorage.setItem('cookie-consent', 'accepted');
      document.body.removeChild(banner);

      // Enable Google Analytics
      window.gtag = window.gtag || function(){dataLayer.push(arguments);};
      gtag('consent', 'update', {
        'analytics_storage': 'granted'
      });
    });

    document.getElementById('decline-cookies').addEventListener('click', function() {
      localStorage.setItem('cookie-consent', 'declined');
      document.body.removeChild(banner);

      // Disable Google Analytics
      window.gtag = window.gtag || function(){dataLayer.push(arguments);};
      gtag('consent', 'update', {
        'analytics_storage': 'denied'
      });
    });
  }
}

document.addEventListener('DOMContentLoaded', showCookieConsent);

4.2 Privacy Policy Page

Create docs/privacy.md:

# Privacy Policy

## Information We Collect

This site uses Google Analytics to analyze access patterns.

### Types of Information Collected

- Page views
- Number of visitors
- Session duration
- Referral sources
- Device information
- Geographic location (country/region level)

### Purpose of Use

- Analyze site usage
- Improve content
- Enhance user experience

## About Cookies

Google Analytics uses the following cookies:

| Cookie Name | Purpose | Retention Period |
|-------------|---------|------------------|
| _ga | User identification | 2 years |
| _ga_* | Session tracking | 2 years |
| _gid | User identification | 24 hours |

## Opt-Out

To disable information collection by Google Analytics:

1. Install the [Google Analytics Opt-out Browser Add-on](https://tools.google.com/dlpage/gaoptout)
2. Disable cookies in your browser settings

## Contact

For privacy-related inquiries, please contact us at [Contact](mailto:your-email@example.com).

5. Reports and Dashboards

5.1 Key Metrics

Main metrics to monitor in Google Analytics:

  1. Realtime
  2. Current active users
  3. Popular pages

  4. Audience

  5. New vs. returning visitors
  6. Access by region
  7. Access by device

  8. Behavior

  9. Popular pages
  10. Average session duration
  11. Bounce rate

  12. Custom Reports

  13. Search keywords
  14. Download counts
  15. External link clicks

5.2 Creating Custom Dashboards

Create a dashboard that consolidates important metrics:

  1. In Google Analytics, go to "Customization" → "Dashboards"
  2. "Create" → "Blank Canvas"
  3. Add the following widgets:
  4. Metrics: Page views, users, sessions
  5. Pie chart: New vs. returning visitors
  6. Table: Popular pages
  7. Timeline: Daily access trends

6. Data Analysis and Site Improvement

6.1 How to Use Analytics

  1. Identify Popular Content

    Behavior → Site Content → All Pages
    

  2. Check Exit Pages

    Behavior → Site Content → Exit Pages
    

  3. Analyze Search Queries

    Behavior → Site Search → Search Terms
    

6.2 Actions for Improvement

Improvement examples based on analysis results:

  1. Popular pages: Enhance related content
  2. High exit pages: Review content, add CTAs
  3. Mobile traffic: Strengthen mobile optimization
  4. Search queries: Create/improve relevant content

7. Troubleshooting

Common Issues

No Data Displayed

# Check configuration
grep -r "G-" mkdocs.yml

Not Reflected in Realtime

  • Confirm deployment is complete
  • Clear browser cache
  • Recheck measurement ID

Private IP Access Not Excluded

// IP address exclusion settings
gtag('config', 'G-XXXXXXXXXX', {
  'custom_map': {'dimension1': 'client_ip'}
});

8. Security and Compliance

8.1 Data Protection

  1. Data Retention Period Settings
  2. GA4 Admin → Data Settings → Data Retention
  3. Recommended: 14 months

  4. IP Anonymization (Automatic in GA4)

  5. User IP addresses are automatically anonymized

  6. Disable Data Sharing

  7. Admin → Account Settings → Data Sharing Settings
  • GDPR compliance (if you have EU visitors)
  • Personal Information Protection Law compliance
  • Cookie Law compliance

Once the basic analytics setup is complete, work on further improvements:

🎨 Site Quality Improvement

📝 Enhance Basic Features

🛠️ Streamline Operations & Maintenance

Analytics Implementation on This Site

This site has Google Analytics 4 already implemented. The "Was this page helpful?" feedback feature at the bottom of each page is also integrated with Analytics.

References