How to Add Google Analytics to Netlify Site

Cody Schneider8 min read

Adding Google Analytics to your Netlify site is one of the first and most important steps to understanding who your visitors are and how they interact with your content. This guide will walk you through several practical methods for getting your site connected, from a simple, no-code option to a more secure approach using environment variables.

Before You Begin: Get Your Measurement ID

Before you can add any code to your site, you need your unique Google Analytics Measurement ID. This tells Google’s servers where to send the tracking data. If you already have your ID (it looks like G-XXXXXXXXXX), you can skip to the next section.

If not, here’s how to find it:

  1. Log into your Google Analytics account.
  2. If you don't have a property for your website yet, you'll be prompted to create one. Follow the on-screen instructions to set up a new Google Analytics 4 property.
  3. If you already have a property, click the gear icon (⚙️ Admin) in the bottom-left corner.
  4. In the Property column, click on Data Streams.
  5. Click on the data stream for your website. (If you don't have one, click "Add stream" and select "Web".)
  6. In the stream details panel, you'll find your Measurement ID in the top-right corner. Click the copy icon next to it to save it to your clipboard.

Now that you have your Measurement ID, you're ready to connect it to your Netlify site. We’ll cover four popular methods.

Method 1: Use Netlify’s Snippet Injection (The Easiest Way)

Netlify has a built-in feature that lets you automatically inject code snippets into every page of your site during the build process. This is the simplest method and doesn't require you to touch your source code.

When to use this method: It's perfect for simple static sites or for anyone who wants a quick, code-free solution.

Step-by-Step Instructions:

  1. Log in to your Netlify dashboard and navigate to the site you want to add Google Analytics to.
  2. Go to Site settings > Build & deploy > Post processing.
  3. Scroll down to the Snippet injection section and click Add snippet.
  4. A configuration window will appear. Fill it out as follows:

The standard Google Analytics 4 script (replace G-XXXXXXXXXX with your ID):

Here is the standard Google Analytics 4 script. Copy this, but be sure to replace `G-XXXXXXXXXX` with your own Measurement ID.
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [],
  function gtag(){dataLayer.push(arguments),}
  gtag('js', new Date()),

  gtag('config', 'G-XXXXXXXXXX'),
</script>

After you paste the code and replace the ID, click Save. Netlify will now automatically add this script to every page on your site after your next deploy. You may need to trigger a new deploy for the changes to take effect.

Method 2: Use Environment Variables (The Most Secure Way)

While snippet injection is easy, hard-coding your Measurement ID directly into the script isn't ideal for security or flexibility. A better practice is to store your ID as an environment variable in Netlify. This keeps your sensitive information out of your Git repository and makes it easy to switch between different analytics properties for staging and production environments.

When to use this method: This is the recommended approach for any site built with modern frameworks like Next.js, Gatsby, or Vue, or any project that has a build step.

Part 1: Set the Environment Variable in Netlify

  1. In your Netlify site’s dashboard, go to Site settings > Build & deploy > Environment.
  2. Under Environment variables, click Add a new variable.
  3. Create a variable named VITE_GA_MEASUREMENT_ID (or NEXT_PUBLIC_GA_MEASUREMENT_ID for Next.js, GATSBY_GA_MEASUREMENT_ID for Gatsby). The prefixes like VITE_ or NEXT_PUBLIC_ are important, as they allow the framework to expose the variable to the browser.
  4. In the Value field, paste your Measurement ID (e.g., G-XXXXXXXXXX).
  5. Click Create variable to save it.

Part 2: Use the Variable in Your Code

Next, you’ll need to modify your site's code to pull this variable during the build process and insert it into the tracking script. The exact implementation depends on your framework.

For Plain HTML (with a simple build process):

If you're using a static site generator or a simple build tool, you'll replace your ID in the script with the environment variable. Here is an example for a JS-based build tool that uses Vite:

<!-- Google tag (gtag.js) -->
<script async src=`https://www.googletagmanager.com/gtag/js?id=${import.meta.env.VITE_GA_MEASUREMENT_ID}`></script>
<script>
  window.dataLayer = window.dataLayer || [],
  function gtag(){dataLayer.push(arguments),}
  gtag('js', new Date()),

  gtag('config', `${import.meta.env.VITE_GA_MEASUREMENT_ID}`),
</script>

For a Next.js App:

In a Next.js project, the best place to add scripts that run on every page is in a custom _document.js file or using the next/script component in _app.js.

In pages/_app.js:

import Script from 'next/script',

function MyApp({ Component, pageProps }) {
  const measurementId = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID,

  return (
    <>
      <Script
        src={`https://www.googletagmanager.com/gtag/js?id=${measurementId}`}
        strategy="afterInteractive" 
      />
      <Script id="google-analytics" strategy="afterInteractive">
        {`
            window.dataLayer = window.dataLayer || [],
            function gtag(){dataLayer.push(arguments),}
            gtag('js', new Date()),
            gtag('config', '${measurementId}'),
        `}
      </Script>
      <Component {...pageProps} />
    </>
  ),
}

export default MyApp,

Using environment variables is a cleaner, more professional approach that will save you headaches down the road.

Method 3: Directly Add the Code to Your HTML File

For the simplest of static sites — perhaps just a single index.html file with some CSS — you can add the tracking code directly into your HTML.

When to use this method: Works for very simple projects without a build step or a shared layout/template file.

Step-by-Step Instructions:

  1. Open your project in your code editor.
  2. Locate your index.html file (or whichever HTML file is the entry point). If you have multiple pages, you'll need to do this for each one unless you are using a templating system.
  3. Find the closing </head> tag.
  4. Paste the full gtag.js script from Google just before it, just like in Method 1.
  5. Remember to replace G-XXXXXXXXXX with your real Measurement ID.
  6. Save the file, commit the changes to your git repository, and push to trigger a new Netlify deploy.

The main drawback here is manual work. If you have ten pages, you need to paste the code ten times. If your Measurement ID ever changes, you have to update it in all ten places.

Method 4: Use Google Tag Manager (for scalability)

As your marketing needs grow, you’ll likely want to add more than just Google Analytics. You might need tags for advertising pixels (Facebook, LinkedIn), heatmaps, and other analytics tools. Managing all these scripts directly in your code can get messy.

This is where Google Tag Manager (GTM) comes in. It’s a free platform that acts as a container for all of your tracking tags. You install the GTM script on your site once, and then you can add, remove, and manage all your other tags from the GTM interface, without ever needing to redeploy your site.

The process involves two main stages:

  1. Add the GTM script to your Netlify site. You can do this using Snippet Injection (Method 1) or by adding it directly to your code (Methods 2 or 3). The principle is identical, you just use the GTM code snippet instead of the Google Analytics one.
  2. Set up a Google Analytics tag inside GTM. Inside the Google Tag Manager interface, you’ll create a new "Google Analytics: GA4 Configuration" tag, paste your Measurement ID there, and set it to fire on all pages.

When to use this method: Best for businesses or marketers who plan to use multiple tracking tools and want a centralized way to manage them without relying on developers.

How to Verify That It's Working

Once you've implemented one of the methods above and your site has been redeployed, you need to check if the analytics tag is firing correctly.

The quickest way is with Google Analytics' Realtime report:

  1. Open your live website (the URL provided by Netlify) in one browser tab. Make sure you don't have any ad blockers active for your domain.
  2. In a separate tab, open your Google Analytics dashboard.
  3. Navigate to Reports > Realtime.
  4. After a minute or two, you should see yourself appear as a user on the map and in the "Users in Last 30 Minutes" card.

If you see your visit, congratulations! You've successfully connected Google Analytics to your Netlify site.

Final Thoughts

Getting Google Analytics set up on Netlify is manageable for any skill level, whether you prefer the no-code snippet injection for a quick start or the more robust environment variable method for a growing application. The important thing is to start collecting data so you can learn from your audience and make better decisions.

Once your data is flowing into Google Analytics, the challenge becomes making sense of it all. Instead of getting lost in complex reports, you need quick answers to your most pressing questions about marketing performance and user behavior. That’s why we built Graphed. It layers on top of your Google Analytics account, allowing you to build real-time dashboards and get instant insights using simple, natural language. Simply ask questions like "which traffic source has the highest conversion rate?" and get clear answers in seconds.

Related Articles

How to Connect Facebook to Google Data Studio: The Complete Guide for 2026

Connecting Facebook Ads to Google Data Studio (now called Looker Studio) has become essential for digital marketers who want to create comprehensive, visually appealing reports that go beyond the basic analytics provided by Facebook's native Ads Manager. If you're struggling with fragmented reporting across multiple platforms or spending too much time manually exporting data, this guide will show you exactly how to streamline your Facebook advertising analytics.

Appsflyer vs Mixpanel​: Complete 2026 Comparison Guide

The difference between AppsFlyer and Mixpanel isn't just about features—it's about understanding two fundamentally different approaches to data that can make or break your growth strategy. One tracks how users find you, the other reveals what they do once they arrive. Most companies need insights from both worlds, but knowing where to start can save you months of implementation headaches and thousands in wasted budget.