Installing the tag with gtag.js

Google Analytics · Essentials · 9 min

No tag, no data: this is the first thing you do on any site, and it decides where every later change happens.

The simplest install is the Google tag snippet, shown in Admin > Data streams > your web stream > View tag instructions. It loads gtag.js asynchronously and configures it with your measurement ID. Put it as high in <head> as possible on every page, including error pages, so page views and timing are consistent.

The snippet does three things: loads the library, defines dataLayer and the gtag() function, and calls gtag('config', 'G-...'), which fires the first page_view and sets the _ga cookie. Options go in the config object: send_page_view: false to control page views yourself, user_id to set a User-ID, debug_mode: true to see events in DebugView.

The alternative is Google Tag Manager (GTM). You place one GTM container snippet on the site and create a Google tag (GA4 configuration) and GA4 event tags inside GTM's web UI. GTM wins when marketing needs to add or change tags without code deploys, or you have many vendors; gtag.js wins for a small site or one that developers fully control. Do not run both for the same measurement ID or every page view is doubled.

Frameworks (Next.js, Nuxt, Gatsby) and CMSs (WordPress, Shopify, Wix) usually have a plugin or a Site Kit-style integration that injects the same snippet; what matters is that exactly one tag with your G- ID runs per page.

After installing, open Realtime or DebugView and load the page: you should see yourself within seconds. Full report data takes 24 to 48 hours to settle.

Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>My shop</title>
  <!-- Google tag (gtag.js): paste on every page, as high in <head> as possible -->
  <script async src="https://www.googletagmanager.com/gtag/js?id=G-ABC123XYZ"></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){ dataLayer.push(arguments); }
    gtag('js', new Date());
    gtag('config', 'G-ABC123XYZ', {
      // optional settings:
      // send_page_view: false,   // you will send page_view yourself (SPA)
      // debug_mode: true         // show this browser in DebugView
    });
  </script>
</head>
<body>
  <h1>Welcome</h1>
</body>
</html>

Remember

  • One Google tag snippet in <head> on every page, or one GTM container
  • gtag('config', ...) fires the first page_view and accepts options
  • Never run gtag.js and a GTM Google tag for the same ID together

Watch out for

  • Installing the snippet twice (theme + plugin) and doubling every page view.

Check yourself

  1. Why is the Google tag placed in <head> rather than at the end of <body>?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developers.google.com/analytics/devguides/collection/ga4