Sub topic 9
Sending the Events with gtag.js or Tag Manager
This chapter covers how to get generate_lead and purchase events from your site into GA4. It assumes you have a GA4 property with a web data stream, Editor access, and basic familiarity with Reports and Admin. It also assumes you have already decided what counts as a lead and a sale, and what parameters each event needs. The next chapter covers marking the events as key events.
Two ways to send the same event
You can send GA4 events from a web page in two ways.
- gtag.js is Google's JavaScript library. You call
gtag('event', ...)directly from your site's code. - Google Tag Manager (GTM) is a container that holds your tags. Your site pushes data into a
dataLayerarray. A GA4 event tag in GTM reads that data and sends it to GA4.
Both methods produce the same hit at GA4's collection endpoint. The difference is who owns the code. With gtag.js, a developer edits the site for every change. With GTM, the site publishes data once, and an analyst can change what is sent without a site release.
Use one method for a given event. If both methods fire the same event, GA4 records it twice.
| Factor | gtag.js | Google Tag Manager |
|---|---|---|
| Where the logic lives | In the site's code | In the GTM container |
| Changes need a site deploy | Yes | No, only a container publish |
| Testing tools | DebugView, browser network tab | GTM Preview mode, DebugView |
| Best fit | Small sites, one developer | Teams that change tracking often |
| Common risk | Event fires from several code paths | Tag and trigger misconfiguration |
How the data flows
The diagram shows both routes ending at the same place.
Prerequisite: the base tag must load first
An event call only works if the GA4 base configuration is already on the page. With gtag.js, that is the snippet from your data stream's tag instructions:
<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>Replace G-XXXXXXXXXX with your own measurement ID. This snippet defines the gtag function. If your event call runs on a page without it, you get gtag is not defined.
With GTM, the equivalent is a Google tag (or GA4 configuration tag) that fires on all pages, plus the GTM container snippet in the site.
Sending a lead with gtag.js
Fire the lead event only after the form has been submitted successfully. Do not fire it on the click of the submit button. A click does not mean the submission passed validation or reached your server.
// Fire after a lead form is successfully submitted
gtag('event', 'generate_lead', {
currency: 'USD',
value: 25.00
});generate_lead is a recommended event. Google defines its name and its parameters. The value here is an estimate of what a lead is worth to you, and currency is a three-letter ISO 4217 code. If you send value, send currency as well. Without a currency, GA4 does not report the value as revenue.
Where to put the call depends on how your form works.
- Form posts to a thank-you page. Fire the event on that page. Guard it so a page refresh does not count a second lead (see the pitfalls below).
- Form submits with JavaScript (AJAX). Fire the event inside the success callback of the request.
document.querySelector('#lead-form').addEventListener('submit', async (e) => {
e.preventDefault();
const response = await fetch('/api/leads', {
method: 'POST',
body: new FormData(e.target)
});
if (response.ok) {
gtag('event', 'generate_lead', { currency: 'USD', value: 25.00 });
}
});Do not copy the visitor's name, email address, or phone number into the event parameters. Google's policies prohibit sending personally identifiable information to Analytics.
Sending a sale with gtag.js
A sale is sent with the purchase event. It needs more parameters than a lead, because GA4 uses them for revenue and item reports.
// Fire once on the order confirmation page
gtag('event', 'purchase', {
transaction_id: 'T_12345',
value: 59.98,
currency: 'USD',
items: [
{
item_id: 'SKU_123',
item_name: 'Trail Shoes',
price: 59.98,
quantity: 1
}
]
});Check these points before you ship it.
transaction_idmust be unique for each order. GA4 uses it to avoid counting the same purchase twice, as covered in the earlier chapter on deduplication.valueis the order total. Decide with your team whether it includes tax and shipping, and keep that choice consistent.itemsmust be an array of objects. Each item needsitem_idoritem_name.- Numbers must be numbers, not strings with currency symbols. Send
59.98, not"$59.98".
The server should render these values into the page. Do not hard-code them as in the example.
Sending the same events through Tag Manager
With GTM, your site pushes an object to the dataLayer. The object has an event key, which GTM uses as a trigger name.
window.dataLayer = window.dataLayer || [];
dataLayer.push({ ecommerce: null }); // clear the previous ecommerce object
dataLayer.push({
event: 'purchase',
ecommerce: {
transaction_id: 'T_12345',
value: 59.98,
currency: 'USD',
items: [
{ item_id: 'SKU_123', item_name: 'Trail Shoes', price: 59.98, quantity: 1 }
]
}
});The first push sets ecommerce to null. The dataLayer merges objects, so without this reset, leftover fields from an earlier ecommerce push could appear in the new event.
Then configure GTM:
- Create a Custom Event trigger. Set the event name to
purchase, matching theeventvalue you push. - Create a GA4 Event tag. Select your Google tag or enter the measurement ID.
- Set the event name to
purchase. - Under the tag's ecommerce settings, turn on Send Ecommerce data and choose Data Layer as the source. GTM then reads the
ecommerceobject. - Attach the Custom Event trigger and save.
For a lead, push { event: 'generate_lead', value: 25, currency: 'USD' }. Create a GA4 Event tag named generate_lead with two event parameters. Map value and currency to Data Layer Variables that read those keys.
Choosing the trigger carefully
The trigger decides when the event fires, and most data quality problems come from it.
| Situation | Reliable trigger | Risky trigger |
|---|---|---|
| Thank-you page after the form | Page View on the thank-you URL | Click on the submit button |
| AJAX form | Custom Event from a `dataLayer` push in the success handler | Form Submission trigger without checking validation |
| Order confirmation | Custom Event `purchase` pushed once by the page | Page View on a URL pattern that also matches the order history |
A Page View trigger on /thank-you also fires when a visitor reloads or bookmarks that URL. For leads, that creates extra events. For sales, transaction_id limits the damage, but it is still better to prevent the extra fire.
Preventing double firing
Duplicates come from a few predictable places.
- Both methods active. A developer added a
gtag('event', 'purchase', ...)call, and GTM also has a purchase tag. Remove one. - Refresh or back button. The confirmation page reloads and the code runs again. Store a flag in
sessionStorageafter the first fire. - Several triggers on one tag. A tag with both a Page View trigger and a Custom Event trigger fires twice.
function sendPurchaseOnce(order) {
const key = 'ga4_sent_' + order.transaction_id;
if (sessionStorage.getItem(key)) return;
sessionStorage.setItem(key, '1');
gtag('event', 'purchase', order);
}Consent and blocked requests
If your site uses a consent banner, the event may be limited until the visitor consents. With Google consent mode, the tags still load but adjust what they store and send, depending on the consent state. Without consent mode, the correct approach is to hold the Google tag until consent is given. Either way, expect that some real leads and sales never appear in GA4. Ad blockers and browser privacy features add to the gap. Treat GA4 counts as a sample that tracks your backend, not as an exact ledger.
Quick checks before moving on
Before you mark anything as a key event, confirm these.
- The base tag loads on every page where events fire.
- Each event name is spelled exactly:
generate_lead,purchase. valueis numeric, andcurrencyis a valid code.transaction_idis different for each order.- Only one method sends each event.
- No personal data appears in any parameter.
A later chapter covers testing in DebugView and Realtime in detail. For now, open your browser's developer tools, go to the Network tab, and filter by collect. Trigger the action. You should see one request whose en parameter is the event name.
Exercise
A site sends purchase from a gtag.js call in its page code. Someone then adds a GTM GA4 Event tag named purchase on the same confirmation page, and reported revenue doubles. Give one reason this can happen even though transaction_id is set, and name the fix.
Show answer
Both methods send the event, so GA4 receives two purchase hits. If the two sources do not send an identical transaction_id, or the duplicate is not caught in processing, revenue can still be counted twice. The fix is to send each event with only one method. Remove either the gtag.js call or the GTM tag, then confirm one collect request per order in the Network tab.
Exercise
A GTM generate_lead tag fires, but the value parameter never appears on the event. The page pushes { event: 'generate_lead', Value: 25, currency: 'USD' }. What is wrong?
Show answer
The key is spelled Value with a capital V, while the tag's Data Layer Variable reads value. Parameter names are case-sensitive, so the variable returns undefined. Change the push to use lowercase value, or change the variable name to match, then check the result in GTM Preview mode.