Sub topic 8
Managing tags with a tag manager and data layer
This chapter assumes you have read the earlier chapters on installing GA4, recording events, and consent. You should also be comfortable with basic JavaScript. By the end you will know how a tag manager separates tracking logic from page code, how the data layer passes information to it, and which mistakes cause duplicate or missing data.
Why use a tag manager
Hard-coding every tracking script into your pages works at first. After a few months you may have GA4, a Meta pixel, a TikTok pixel, and a LinkedIn tag, each with its own event calls. Every change then needs a developer, a code review, and a deploy.
A tag manager moves that work out of the page. You install one container snippet once. After that, you add, change, and remove tags in the tag manager's web interface. Google Tag Manager (GTM) is the most common choice, and this chapter uses its vocabulary.
A tag manager does not collect data itself. It runs other tools' code at the right moment, using rules you define.
The three building blocks
GTM organizes everything into three object types.
| Object | What it is | Social media example |
|---|---|---|
| Tag | A piece of code or a configuration that sends data somewhere | A GA4 event tag that sends `generate_lead` |
| Trigger | The condition that makes a tag fire | A custom event named `generate_lead` appears in the data layer |
| Variable | A named value that tags and triggers can read | `form_id`, or the value of the `utm_source` cookie |
A tag does nothing until a trigger fires it. A tag with no values to send is less useful, which is why variables matter.
The data layer
The data layer is a JavaScript array, window.dataLayer. Your page pushes plain objects onto it, and the tag manager watches the array and reacts to each push. The data layer gives developers a stable contract: the page announces what happened, and marketers decide what to do about it.
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'generate_lead',
form_id: 'newsletter_footer'
});The event key is special. A push containing event can fire triggers. A push without it only updates stored values, which later events can read.
The window.dataLayer = window.dataLayer || [] line matters. It creates the array if it does not exist yet, so your code works whether it runs before or after the container loads. Always include it before any push.
Where the data layer lives in a page
Push page-level values before the container snippet, so they are available when the first triggers evaluate. Push interaction events later, when they happen.
<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
page_type: 'landing',
campaign_theme: 'spring_sale'
});
</script>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXXX');</script>Replace GTM-XXXXXXX with your container ID. GTM also supplies a noscript iframe to place right after the opening body tag. It covers visitors without JavaScript, and you can usually skip it if your audience always has scripts enabled.
From click to tag: the flow
The diagram shows how one form submission travels to several destinations through the data layer.
Both tags reuse the same push. You write the page code once, and sending the same event to another platform later is a configuration change.
Building a lead event in GTM
Suppose the page already pushes the generate_lead event shown above. In the GTM interface, you would do the following.
- Create a Data Layer Variable named
dlv - form_id, with the data layer variable nameform_id. - Create a Custom Event trigger. Set the event name to
generate_lead, matching exactly. - Create a GA4 Event tag. Set the event name to
generate_lead, add an event parameterform_idwith the value{{dlv - form_id}}, and attach the trigger from step 2. - Open Preview mode, submit the form, and confirm the tag fired.
- Publish a new container version.
Then mark generate_lead as a key event in the GA4 admin, as covered earlier. Reports by source and medium will now show leads per UTM-tagged campaign.
Ecommerce pushes and clearing stale values
The data layer merges new pushes into what is already stored. This causes a classic bug with nested objects such as ecommerce data. If one push has an items array and a later push has a different one, leftover fields may survive. Google's guidance is to clear the object before each ecommerce push.
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({ ecommerce: null });
window.dataLayer.push({
event: 'purchase',
ecommerce: {
transaction_id: 'T-1042',
value: 59.9,
currency: 'USD',
items: [{ item_id: 'SKU-17', item_name: 'Trail Shoe', price: 59.9, quantity: 1 }]
}
});Carrying UTM values forward
Visitors from social posts arrive with UTM parameters in the URL, but the query string disappears on the next page. A common pattern is to read the UTMs on the landing page, store them, and push them to the data layer when a conversion occurs.
const stored = JSON.parse(sessionStorage.getItem('utm') || '{}');
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'generate_lead',
form_id: 'newsletter_footer',
lead_utm_source: stored.utm_source || '(none)',
lead_utm_campaign: stored.utm_campaign || '(none)'
});This code assumes an earlier script saved the values into sessionStorage, like the one in the UTM chapter. GA4 attributes sessions to campaigns on its own. These extra parameters matter when you copy the lead into a CRM or send it to another system that cannot see GA4's attribution.
Working safely: workspaces, versions, and preview
GTM changes nothing on your live site until you publish. Use that safety net.
- Preview mode opens a debug panel showing each event, which tags fired, and the data layer's state at that moment.
- Versions let you roll back to a known-good container when a change breaks tracking.
- Workspaces let several people edit in parallel without overwriting each other.
- Names and notes prevent confusion months later. Use a pattern such as
GA4 - event - generate_leadand describe why the tag exists.
Limit publish permission to people who understand the impact. A container runs on every page, so a bad tag can slow the site or leak data.
Consent and tag managers
A tag manager makes it easy to add tags, and just as easy to add tags that ignore consent. Configure consent in the container, so tags wait for the visitor's choice. Set the consent defaults to denied before any tag fires, and update them when the visitor accepts, as shown in the consent chapter. For each non-Google tag, such as an ad pixel, set required consent types in its advanced settings. A pixel that fires before the banner is answered is a compliance problem, even if the GA4 tag is configured correctly.
Common errors
- Double counting. You leave a hard-coded
gtag('config', ...)snippet on the page and also add a GA4 configuration in GTM. Page views arrive twice. Use one installation method. - Name mismatches. Trigger event names are case-sensitive.
Generate_Leadin the trigger will never matchgenerate_leadin the push. - Pushing too late or too early. If a page redirects right after submit, the tag may not finish sending. If a value is pushed after the event that needs it, the variable reads as undefined. Push values first, or include them in the same object as the event.
- The "All Pages" habit. Attaching a pixel to the All Pages trigger fires it on thank-you and error pages alike. Use specific triggers for conversion tags.
- Single-page apps. The page does not reload when the route changes, so the standard page view trigger fires only once. Push a virtual page view event on route changes, or use the History Change trigger.
- Typos in IDs. A wrong measurement ID sends data to the wrong property or nowhere. Store IDs in constants variables and reference them.
- Forgetting to publish. Preview mode shows unpublished changes working. Live visitors see nothing new until you publish.
When not to use a tag manager
A tag manager adds a layer to learn and maintain. A tiny site with one GA4 tag and two events may be simpler with direct gtag calls. The trade-off flips when more than one platform needs the same events, when non-developers manage campaigns, or when you need versioned change control. Also, ad blockers often block the GTM script itself, which is one reason server-side options exist, covered in a later chapter.
Exercise
A visitor submits your newsletter form. Your page pushes { event: 'generatelead', formid: 'newsletterfooter' } and you have a GA4 event tag named generatelead with a Custom Event trigger set to "GenerateLead". Preview mode shows the push but the tag did not fire. What is wrong, and how would you fix it so the formid also reaches GA4?
Show answer
The trigger's event name does not match the pushed name, because trigger matching is case-sensitive. Change the trigger to generatelead, or change the push to match. To send formid, create a Data Layer Variable for formid and add it to the GA4 tag as an event parameter with the value {{dlv - formid}}. Then re-test in Preview mode and publish.