Google Analytics Setup Guide¶
This guide provides detailed instructions on how to integrate Google Analytics into your MkDocs Material site for access analysis.
Prerequisites
- You have completed How to Create GitHub Pages with MkDocs
- You have a Google account
1. Google Analytics 4 (GA4) Setup¶
1.1 Creating a Google Analytics Account¶
- Access Google Analytics
- Click "Start measuring"
- Enter an account name (e.g., My Documentation Site)
- Review account settings
- Click "Next"
1.2 Property Setup¶
- Enter a property name (e.g., MkDocs Site)
- Set reporting time zone to "Japan"
- Set currency to "Japanese Yen"
- Click "Next"
1.3 Business Details¶
- Select an industry category (e.g., "Computers & Electronics")
- Select business size
- Click "Create"
1.4 Data Stream Setup¶
- Select "Web"
- Enter your website URL
https://username.github.io/repository-name/ - Enter a stream name (e.g., GitHub Pages Site)
- Click "Create stream"
1.5 Obtaining the Measurement ID¶
After creation is complete, copy the Measurement ID (in the format G-XXXXXXXXXX).

2. Implementation in MkDocs¶
2.1 Basic Setup (Recommended)¶
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¶
4.1 Cookie Consent Banner¶
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:
- Realtime
- Current active users
Popular pages
Audience
- New vs. returning visitors
- Access by region
Access by device
Behavior
- Popular pages
- Average session duration
Bounce rate
Custom Reports
- Search keywords
- Download counts
- External link clicks
5.2 Creating Custom Dashboards¶
Create a dashboard that consolidates important metrics:
- In Google Analytics, go to "Customization" → "Dashboards"
- "Create" → "Blank Canvas"
- Add the following widgets:
- Metrics: Page views, users, sessions
- Pie chart: New vs. returning visitors
- Table: Popular pages
- Timeline: Daily access trends
6. Data Analysis and Site Improvement¶
6.1 How to Use Analytics¶
Identify Popular Content
Behavior → Site Content → All PagesCheck Exit Pages
Behavior → Site Content → Exit PagesAnalyze Search Queries
Behavior → Site Search → Search Terms
6.2 Actions for Improvement¶
Improvement examples based on analysis results:
- Popular pages: Enhance related content
- High exit pages: Review content, add CTAs
- Mobile traffic: Strengthen mobile optimization
- 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¶
- Data Retention Period Settings
- GA4 Admin → Data Settings → Data Retention
Recommended: 14 months
IP Anonymization (Automatic in GA4)
User IP addresses are automatically anonymized
Disable Data Sharing
- Admin → Account Settings → Data Sharing Settings
8.2 Legal Requirements¶
- GDPR compliance (if you have EU visitors)
- Personal Information Protection Law compliance
- Cookie Law compliance
📚 Related Articles & Next Steps¶
Once the basic analytics setup is complete, work on further improvements:
🎨 Site Quality Improvement¶
- Design Improvement Guide - Improve analytics metrics by enhancing user experience
- Advanced Configuration - Improve page load speed through performance optimization
📝 Enhance Basic Features¶
- MkDocs Creation Guide - Review the basic site structure
🛠️ Streamline Operations & Maintenance¶
- Useful Tools - Streamline data analysis and operational tasks
- crontab Setup - Automate periodic report generation
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.