Table of Contents
Adding Google Analytics to your Hugo website allows you to track visitor behavior, monitor traffic sources, and improve your site’s performance. In this guide, we’ll walk through the steps to integrate Google Analytics with Hugo.
Step 1: Create a Google Analytics Account
If you haven’t already, sign up for a Google Analytics account at analytics.google.com. Use your Google account to log in or create a new one. Once logged in, set up a new property for your website.
Step 2: Get Your Tracking ID
After creating your property, Google Analytics will provide a Tracking ID, which looks like UA-XXXXXXXXX-X. Copy this ID; you’ll need it to configure your Hugo site.
Step 3: Add the Tracking Code to Your Hugo Site
Hugo sites typically include a head partial or template. You need to insert the Google Analytics tracking script into this section.
Open your Hugo project’s layouts/partials folder and locate or create a file named head.html. Add the following code, replacing YOUR_TRACKING_ID with your actual Tracking ID:
<!-- Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=YOUR_TRACKING_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'YOUR_TRACKING_ID');
</script>
Step 4: Rebuild Your Hugo Site
Save your changes and run the command hugo in your terminal to rebuild your website. The Google Analytics script will now be included on all pages.
Step 5: Verify the Setup
Visit your website and go to the Google Analytics dashboard. Use the Real-Time report to check if your visit is being tracked. If you see your activity, the setup is successful.
Additional Tips
- Use a content security policy to allow Google Analytics scripts if you have strict security settings.
- Consider using environment variables or configuration files to manage your Tracking ID securely.
- Regularly check your Google Analytics reports to monitor your website’s performance.