Sub topic 9
Implementing events with gtag.js
This chapter shows how to send recommended and custom events from a web page with gtag.js, the Google tag library. It assumes you can read JavaScript objects and function calls, you have a GA4 property with a web data stream, and you know the difference between recommended and custom events from earlier chapters. Google Tag Manager is covered in the next chapter.
How gtag() works
The Google tag snippet does two things. It loads the gtag.js library from Google, and it defines a small gtag() function that adds commands to a queue named dataLayer. When the library finishes loading, it reads the queue and sends the matching hits to GA4.
<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 the measurement ID of your web data stream. Three details are worth knowing:
gtag()pushes theargumentsobject, not an array. If you rewrite the function with rest parameters or push an array yourself, the library ignores the command.- Because commands are queued, you can call
gtag('event', ...)before the library has loaded. The event is sent once the library starts. - The
configcommand sends apage_viewby default, and the stream's enhanced measurement settings still apply.
The event command
Every event uses the same shape:
gtag('event', '<event_name>', { <parameter_name>: <value>, ... });The first argument is always the string 'event'. The second is the event name, which is case-sensitive, so Login and login are different events. The third is an optional object of event parameters.
Sending a recommended event
A recommended event uses a name and parameters that Google has defined, so GA4 can map them into standard reports. The login event takes one recommended parameter, method.
gtag('event', 'login', {
method: 'Google'
});Send this when the login succeeds, not when the user clicks the button. A click shows intent, and a successful login is the outcome you want to count.
The purchase event
purchase is the most demanding recommended event. It needs a transaction ID, a value, a currency, and an items array.
gtag('event', 'purchase', {
transaction_id: 'T_12345',
value: 59.98,
currency: 'USD',
items: [
{
item_id: 'SKU_123',
item_name: 'Trail Shoes',
price: 29.99,
quantity: 2
}
]
});Points to check:
valuemust be a number, not a string such as'59.98'. Strings can be dropped or mis-typed in revenue reports.currencymust be a three-letter ISO 4217 code. If you sendvaluewithoutcurrency, the revenue is not reported correctly.transaction_idshould be unique per order. GA4 uses it to avoid counting the same purchase twice, but only if you send the same ID. A new random ID on each page reload defeats that.- Each object in
itemsneedsitem_idoritem_name. Addpriceandquantityso item-level revenue is correct. - Fire
purchaseonce, on the confirmation page or after the payment callback. Guard against reloads, for example by storing the transaction ID insessionStorageand skipping IDs you already sent.
Sending a custom event
Use a custom event when no recommended event describes the interaction. Choose a snake_case name that says what happened, and keep parameters flat and simple.
gtag('event', 'newsletter_signup_click', {
placement: 'footer',
plan_type: 'free'
});In practice you attach the call to a real interaction:
document.querySelectorAll('[data-newsletter-cta]').forEach(function (button) {
button.addEventListener('click', function () {
gtag('event', 'newsletter_signup_click', {
placement: button.dataset.placement || 'unknown',
plan_type: 'free'
});
});
});Keep these limits in mind. They apply to standard properties and can change, so check Google's current documentation:
- Event names and parameter names can be up to 40 characters. They must start with a letter and contain only letters, numbers, and underscores.
- A parameter value can be up to 100 characters.
- One event can carry up to 25 parameters.
- Do not use reserved names such as
first_visitorsession_start, or reserved prefixes such asgoogle_,ga_, andfirebase_. GA4 silently drops such events. - Never send personally identifiable information such as email addresses or phone numbers as parameter values.
Parameters shared by many events
You rarely want to repeat the same parameter on every call. gtag has two commands for this.
// Applies to every later event from this page
gtag('set', {
site_section: 'blog'
});
// Applies to the config and all later events for this measurement ID
gtag('config', 'G-XXXXXXXXXX', {
content_group: 'tutorials'
});Parameters on an individual event override a set value with the same name. Use set for page-level context and per-event parameters for what is specific to one action.
User properties describe the user rather than the action. They are set separately:
gtag('set', 'user_properties', {
membership_tier: 'gold'
});A user property is sent along with subsequent events, so set it as early as you know the value.
Timing and delivery
Events that fire as the page unloads, such as a click on a link that leaves your site, can be cancelled by the browser. Two options help:
- Add
transport_type: 'beacon'to the event parameters so the request is sent with the Beacon API, which survives navigation. - Use
event_callbackand navigate only after it runs, withevent_timeoutas a safety limit:
function trackAndGo(url) {
var done = false;
function go() {
if (done) return;
done = true;
window.location.href = url;
}
gtag('event', 'outbound_link_click', {
link_url: url,
event_callback: go,
event_timeout: 1000
});
setTimeout(go, 1000);
}The extra setTimeout covers cases where gtag never loads, for example when an ad blocker is active. Without it, the visitor would never reach the link.
Also remember that gtag only sends data if the library loaded and consent settings allow it. If you use Consent Mode, analytics_storage set to denied changes what is collected.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Event never appears | Name starts with a digit, contains spaces, or uses a reserved name | Rename to a valid snake_case name |
| Event appears, parameter missing in reports | Parameter was never registered as a custom dimension or metric | Register it, as covered in a later chapter |
| Revenue is 0 or missing | `value` sent as a string, or `currency` missing | Send a number and a three-letter currency code |
| Purchases counted twice | Page reloads re-run the call, or `transaction_id` changes each time | Send a stable ID and guard against repeat calls |
| Two events with similar names | Inconsistent case, such as `Signup` and `signup` | Agree names in a tracking plan |
| Outbound clicks undercounted | Navigation cancels the request | Use `transport_type: 'beacon'` or `event_callback` |
| `gtag is not defined` | Event code runs before the snippet, or the snippet is blocked | Place the snippet first in `<head>` and guard calls if needed |
Testing while you build
Add debug_mode: true to an event or to the config command, and the event shows in the DebugView report in GA4 in near real time. For example:
gtag('event', 'login', {
method: 'Google',
debug_mode: true
});Remove it before release, or limit it to your own test traffic. The chapter on DebugView covers this in detail.
Exercise
A checkout page calls gtag('event', 'purchase', { transaction_id: String(Date.now()), value: '59.98', items: [...] }) every time it loads. Name three problems and give the fix for each.
Show answer
First, transaction_id is new on every load, so reloads create duplicate purchases. Use the real order ID from your backend and skip IDs already sent. Second, value is a string, so revenue may not be recorded correctly. Send the number 59.98. Third, currency is missing, so revenue cannot be attributed to a currency. Add currency: 'USD' or the correct ISO 4217 code.
Exercise
You need to record clicks on a "Download brochure" button, and no recommended event fits. Write the gtag call, using a valid name and one parameter that says which brochure was requested.
Show answer
gtag('event', 'brochuredownloadclick', { brochurename: 'springcatalog' }); The name is snakecase, under 40 characters, and not reserved. The parameter name is lowercase with no spaces. To use brochurename in reports, register it as an event-scoped custom dimension.