How to Add Google Analytics to Gatsby
You've built a blazing-fast site with Gatsby, and now you need to know who's visiting, where they're coming from, and what they're doing. The best way to get these answers is by adding Google Analytics. This guide will walk you through exactly how to connect Google Analytics 4 with your Gatsby site, giving you the power to make data-driven decisions about your content and marketing.
Why Bother with Analytics on Your Gatsby Site?
Before jumping into the code, it’s worth a quick refresher on why this is so important. A website without analytics is like flying a plane without any instruments - you’re moving, but you have no idea where you're going or why.
Connecting Google Analytics allows you to:
- Understand Your Audience: See where your visitors are located, what devices they use (mobile vs. desktop), and get basic demographic information. This helps you tailor your content to the people who are actually reading it.
- Track Content Performance: Find out which blog posts, landing pages, or product pages are the most popular. You can see which content drives engagement and which pages cause visitors to leave.
- Analyze Traffic Sources: Discover how people are finding your site. Are they coming from Google search, a social media post, a paid ad, or a link from another website? This insight is vital for focusing your marketing efforts.
- Measure Conversions and Goals: If you want visitors to take a specific action - like signing up for a newsletter, filling out a contact form, or making a purchase - analytics helps you track those conversions and see how effectively your site is achieving its goals.
In short, analytics turns visitors from anonymous numbers into actionable insights that can help you grow your business.
Before You Start: Get Your GA4 Measurement ID
To connect Gatsby with Google Analytics, you’ll need one key piece of information: your Measurement ID. This is the unique identifier for your website's data stream in Google Analytics 4.
Understanding Your Tracking ID
If you’ve used Google Analytics in the past, you might be familiar with Tracking IDs that started with "UA-". That was for the old Universal Analytics, which has been officially sunset by Google. The new standard is Google Analytics 4, and its identifier is called a Measurement ID, which always starts with "G-". For this tutorial, we will only be focusing on the current GA4 standard.
If you don't have a Google Analytics 4 property yet, head over to the Google Analytics site and create a new account and property first. The setup process will guide you to create a "data stream" for your website, where you'll find the Measurement ID.
How to Find Your GA4 Measurement ID
If you already have a GA4 property set up, finding your ID is simple. Just follow these steps:
- Log in to your Google Analytics account.
- Click on the Admin gear icon in the bottom-left corner.
- In the Property column, make sure the correct property is selected, then click on Data Streams.
- Click on the data stream corresponding to your website. Usually, you'll only have one.
- In the top right corner of the stream details, you'll see your Measurement ID. It will look something like
G-XXXXXXXXXX. Copy this value - you'll need it in a moment.
Adding Google Analytics to Gatsby: The Easiest Method
The Gatsby ecosystem is built on a rich library of plugins, and thankfully, adding Google Analytics has been made incredibly simple by a dedicated community-maintained plugin. We'll be using gatsby-plugin-google-gtag, which uses Google's latest global site tag (gtag.js) and is the recommended way to implement GA4.
This approach is better than manually adding the script tag to your HTML because the plugin is designed to work seamlessly with Gatsby's build process and client-side routing, ensuring that page views are tracked correctly even as users navigate around your single-page application without full page reloads.
Step 1: Install the gatsby-plugin-google-gtag Plugin
First, you need to add the plugin to your project. Open your terminal, navigate to your Gatsby project's root directory, and run the command that matches your package manager:
If you're using npm:
npm install gatsby-plugin-google-gtag
If you're using yarn:
yarn add gatsby-plugin-google-gtag
Step 2: Configure the Plugin in gatsby-config.js
Next, you need to tell Gatsby to use the plugin and provide your Measurement ID. Open the gatsby-config.js file at the root of your project. Inside the plugins array, add the following configuration object:
module.exports = {
siteMetadata: {
title: `My Awesome Gatsby Site`,
// ...other metadata
},
plugins: [
// ...other plugins
{
resolve: `gatsby-plugin-google-gtag`,
options: {
// You can add multiple tracking ids and a pageview event will be fired for all of them.
trackingIds: [
"YOUR_GA_MEASUREMENT_ID", // Google Analytics / GA
],
// This object gets passed directly to the gtag config command
// This is an optional object
gtagConfig: {
anonymize_ip: true,
cookie_expires: 0,
},
// This object is used for configuration specific to this plugin
pluginConfig: {
// Puts tracking script in the head instead of the body
head: true,
// Setting this parameter is also optional
respectDNT: true,
},
},
},
// ...more plugins
],
}Make sure to replace "YOUR_GA_MEASUREMENT_ID" with the actual Measurement ID you copied earlier. Once you've saved the file, restart your Gatsby development server (gatsby develop) for the changes to take effect.
Step 3: Test and Verify the Installation
Now for the most important step: checking that it actually works. There are two primary ways to confirm that Google Analytics is successfully tracking your site.
Method 1: Browser Developer Tools
- Open your Gatsby site in a browser (e.g., at
localhost:8000). - Open the developer tools (Right-click -> Inspect, or press
Cmd+Opt+Ion Mac /Ctrl+Shift+Ion Windows). - Click on the Network tab.
- In the filter box, type
gtag. - Refresh the page. You should see a request being made to a URL that includes
collect?v=2&,tid=G-XXXXXXXXXX...whereG-XXXXXXXXXXis your Measurement ID. If you see this request, it means your browser has sent a pageview hit to Google Analytics.
Method 2: Google Analytics Realtime Report
This method offers undeniable proof that Google's servers are receiving your data.
- Go back to your Google Analytics dashboard.
- In the left-hand navigation, go to Reports > Realtime.
- With the Realtime report open, visit your Gatsby site in another browser window or tab.
- Within a minute or two, you should see yourself appear as a visitor on the map and in the "Users in last 30 minutes" card. You can even click around your site to different pages and see the page titles and events update in real time.
If you see your activity, congratulations! You have successfully added Google Analytics to your Gatsby site.
Going Beyond Pageviews: Advanced Analytics in Gatsby
Basic pageview tracking is great, but to get a deeper understanding of user behavior, you'll want to track specific interactions as custom events.
Tracking Custom Events
A custom event is any interaction you want to measure that isn't an automatic pageview. Examples include newsletter signups, file downloads, or clicks on a specific call-to-action button.
The gatsby-plugin-google-gtag plugin makes the global gtag function available on the window object in the browser. You can call this function from any React component to send a custom event. Here’s an example of how to track a click on a "Get Started" button:
import React from "react",
const CtaButton = () => {
const handleCtaClick = () => {
if (typeof window.gtag === 'function') {
window.gtag("event", "cta_click", {
event_category: "engagement",
event_label: "Get Started Header Button",
}),
}
},
return (
<button onClick={handleCtaClick}>
Get Started
</button>
),
},
export default CtaButton,In this snippet:
- The check
if (typeof window.gtag === 'function')is a good practice to prevent errors during the Gatsby build process when thewindowobject isn't available. window.gtag("event", "cta_click", ...)sends an event with the namecta_click. You can then see this event show up in your Google Analytics reports.
Respecting User Privacy with Cookie Consent
With regulations like GDPR and CCPA, you must often get user consent before you can place tracking cookies on their browser. You can manage this in Gatsby by adding another plugin, gatsby-plugin-gdpr-cookies.
1. Install the Plugin:
npm install gatsby-plugin-gdpr-cookies
2. Configure Both Plugins Together:
Arrange your gatsby-config.js so that the GDPR plugin comes before the Google Analytics plugin. This order is important. The GDPR plugin will enable or disable the tracking scripts based on user consent.
module.exports = {
plugins: [
// ...other plugins
{
resolve: `gatsby-plugin-gdpr-cookies`,
options: {
googleAnalytics: {
trackingId: 'YOUR_GA_MEASUREMENT_ID', // Don't anonymize in GDPR plugin if using other plugin
anonymize: false
},
// Defines the environments where the Gatsby script will be loaded.
environments: ['production', 'development']
},
},
{
resolve: `gatsby-plugin-google-gtag`,
options: {
trackingIds: [
"YOUR_GA_MEASUREMENT_ID"
],
// The GDPR plugin will handle adding the script if consent is given
// So we delay the gtag script in this plugin
pluginConfig: {
head: true,
respectDNT: true,
delayOnRouteUpdate: 200 // Wait 200ms
},
}
}
// ...other plugins
],
}Now, when a user first visits your site, they'll see a cookie consent banner. Google Analytics will only be activated if they accept.
Final Thoughts
Adding Google Analytics to a Gatsby site is a straightforward process when you use the right plugin. By following these steps, you’ve moved beyond guesswork and can now use real data to understand your audience, measure your content's effectiveness, and track the goals that matter most to your business.
Of course, after collecting all this valuable data, the next step is making sense of it. While Google Analytics is powerful, its interface can be overwhelming for many. We built Graphed to solve this by connecting directly to your tools like Google Analytics. Instead of digging through complex reports, you can just ask questions in plain English, like "Show me my top landing pages from organic search traffic last month," and get instant answers, charts, and dashboards in real-time. It completely automates the manual busywork of analysis and reporting.
Related Articles
What SEO Tools Work with Google Analytics?
Discover which SEO tools integrate seamlessly with Google Analytics to provide a comprehensive view of your site's performance. Optimize your SEO strategy now!
Looker Studio vs Metabase: Which BI Tool Actually Fits Your Team?
Looker Studio and Metabase both help you turn raw data into dashboards, but they take completely different approaches. This guide breaks down where each tool fits, what they are good at, and which one matches your actual workflow.
How to Create a Photo Album in Meta Business Suite
How to create a photo album in Meta Business Suite — step-by-step guide to organizing Facebook and Instagram photos into albums for your business page.