Sub topic 8
Installing the tag with gtag.js, Tag Manager, or a CMS
This chapter assumes you have a Google Analytics 4 property with a web data stream and can find its measurement ID, which looks like G-XXXXXXXXXX. It also assumes you can edit a site's page template, use a tag manager, or install a CMS plugin. The tag is the piece of JavaScript that connects your pages to the data stream. Without it, the stream exists but receives nothing.
What the tag does
The Google tag loads a library called gtag.js from Google's servers. Once loaded, it does three things:
- It reads the measurement ID you give it and ties every hit to that data stream.
- It sets a first-party cookie (by default,
_ga) that identifies a browser across visits. - It sends a
page_viewevent, plus any enhanced measurement events you switched on for the stream, to Google's collection endpoint.
You have three common ways to put the tag on a site. Pick one per site. Running two methods at once is the most frequent cause of inflated numbers, as covered later in this chapter.
| Method | Best when | Edit the page template? | Main trade-off |
|---|---|---|---|
| gtag.js snippet | Small or custom sites, one developer | Yes | Every change to tags needs a code deploy |
| Google Tag Manager (GTM) | Several tags, non-developers editing tags | Once, to add the container | Extra layer to learn and keep tidy |
| CMS integration | WordPress, Shopify, Wix and similar | No | Limited control, depends on the plugin |
Method 1: the gtag.js snippet
Find the snippet in the GA4 Admin area: open Admin, then Data streams, select your web stream, then View tag instructions, then Install manually. Google shows the snippet with your measurement ID filled in.
Paste it as high as possible inside the <head> element of every page, ideally in a shared layout or template so you edit it once.
<!-- 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>Each part has a job:
- The first
scripttag loads gtag.js. Theasyncattribute lets the page keep rendering while the file downloads. window.dataLayeris an array that queues commands. Creating it with|| []means existing content is kept if another script already made it.gtag()pushes itsargumentsobject ontodataLayer. It must pusharguments, not an array of its arguments, because the library parses that specific shape. Rewriting the function in a "cleaner" way breaks it silently.gtag('js', new Date())records the load time.gtag('config', 'G-XXXXXXXXXX')attaches this page to the data stream and triggers the automaticpage_view.
Replace G-XXXXXXXXXX in both places with your own ID. A mismatch between the two is a common typo, and the data then goes to whichever ID the config call names.
Sending events beyond the automatic ones
Enhanced measurement covers page views, scrolls, outbound clicks and a few more. Anything else, such as a sign-up, needs an explicit event call. Because the snippet already defines gtag(), you can call it anywhere after the snippet runs:
gtag('event', 'sign_up', {
method: 'email'
});sign_up is one of Google's recommended event names, and method is its documented parameter. Using recommended names means standard reports and later features recognise the event without extra setup.
Method 2: Google Tag Manager
Google Tag Manager is a separate product with its own account and container. You add a small container snippet to the site once. After that, you add, change, and remove tags in the GTM web interface and publish them without touching the site's code.
The setup has four steps:
- Create a GTM account and a Web container at tagmanager.google.com.
- Install the two container snippets GTM gives you. One goes high in
<head>. The other, anoscriptiframe, goes right after the opening<body>tag. - In the container, create a new tag of type Google tag. Enter your measurement ID as the Tag ID and set the trigger to Initialization - All Pages.
- Use Preview to test, then Submit and publish the container.
Publishing matters. A saved but unpublished workspace changes nothing on the live site, and this trips up many first-time users.
With GTM, you send custom events using a separate GA4 Event tag, or a Google tag event setting, fired by a trigger. The page itself pushes data into dataLayer and GTM reads it.
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'sign_up',
method: 'email'
});This code does nothing for GA4 on its own. It becomes a GA4 event only when the container has a Custom Event trigger named sign_up and a tag that uses it.
Sequence of loading with GTM
Method 3: a CMS or platform integration
Many platforms ask only for the measurement ID, and some also accept a GTM container ID. Typical routes are:
- WordPress: an analytics plugin, or a theme setting. Site Kit by Google is Google's own plugin.
- Shopify, Wix, Squarespace, Webflow: a built-in "Google Analytics" or "tracking code" field in the site settings.
Enter the G- ID exactly. Do not paste a Universal Analytics ID (it starts with UA-). Universal Analytics stopped processing data in 2023, so a UA- ID collects nothing in GA4.
Check two things before you rely on a plugin. First, that it does not also inject its own tag if you pasted the snippet by hand. Second, what it does with logged-in users or admin pages. Some plugins skip them, which changes your numbers compared with a manual install.
Common errors and how to avoid them
- Duplicate installation. If both a hard-coded gtag.js snippet and a GTM Google tag use the same ID, each page view is counted twice. Page views per session look too high and bounce-related figures look too good. Search the page source for your ID. It should appear in one installation path only.
- Tag in the wrong place. A snippet in the footer loads late and misses visitors who leave quickly. Put it in
<head>. - Missing pages. A tag in a template used by most pages but not by, for example, a checkout hosted elsewhere leaves gaps. Compare page counts against your sitemap.
- Single-page applications. In frameworks such as React, the browser does not reload between views. The tag fires once on first load. With enhanced measurement's "Page changes based on browser history events" option enabled, GA4 records route changes. If your router does not use the History API normally, send
page_viewevents yourself. - Content blockers. Ad blockers and some browsers prevent gtag.js from loading. Some share of real visits will never appear, so treat GA4 counts as a close estimate and not an exact census.
- Consent tools that block the tag. A consent banner may hold the tag until the visitor agrees. That is intended, but it means a test in a fresh browser shows nothing until you accept. Consent settings are covered in a later chapter.
Test before you trust
After installing, confirm that data arrives. Two tools exist for this, and both are covered in the next chapter on verification. A quick check is available now:
- Open your site in a normal browser window.
- In GA4, go to Reports, then Realtime.
- Within about a minute you should see at least one user and a
page_viewevent.
For detailed inspection, add debug_mode to the config call. This makes your events show up in DebugView, where you see each event and its parameters as they arrive.
<script>
gtag('config', 'G-XXXXXXXXXX', {
'debug_mode': true
});
</script>This replaces the plain config line, so you do not call config twice for the same ID. Remove debug_mode after verification. Leaving it on adds debug traffic to the stream and clutters DebugView for everyone else.
Choosing a method
Use the plain snippet when the site is small, one person owns the code, and you only need a handful of events. Choose GTM when marketing or analytics staff need to change tags without a release, or when you will add other tags such as advertising pixels. Use a CMS integration when the platform offers it and you do not need custom code, but move to GTM when plugin limits start to block you.
Changing method later is possible. Remove the old installation first, then add the new one, and verify that page views are not doubled.
Exercise
A site has a hard-coded gtag.js snippet in its head. A marketer then adds a Google tag with the same measurement ID in a GTM container, and publishes it. The site has no other changes. Realtime now shows roughly twice the expected page views. What is the cause, and how do you fix it?
Show answer
The same ID is installed through two paths, so each page load sends two page_view events. Keep one path. Either remove the hard-coded snippet and rely on GTM, or unpublish the GTM Google tag. Then reload the site, check the Network tab for a single collect request per page view, and confirm in Realtime.
Exercise
You push { event: 'sign_up', method: 'email' } to dataLayer on a site that uses GTM, but no sign_up event appears in GA4. Name two things to check in the container.
Show answer
First, check that a Custom Event trigger exists with the event name exactly sign_up, since names are case-sensitive. Second, check that a GA4 event tag using that trigger exists and that the container version containing it has been published, not only saved in the workspace. Preview mode shows whether the trigger fired.