Sub topic 2
Custom events: when nothing predefined fits
Prerequisites: This chapter assumes you know the GA4 interface, have a web data stream with a Measurement ID (format G-XXXXXXXXXX), can add a script to a web page, and understand JavaScript objects and function calls.
GA4 records every interaction as an event. Automatically collected events such as page_view and enhanced measurement events such as scroll need no custom code. Recommended events have predefined names and parameters, such as login or purchase. A custom event is a name you define for an interaction that no predefined event describes.
Naming rules, reserved names, and limits
Apply these rules to custom event names and parameter names:
- Use only letters, numbers, and underscores. Start with a letter.
- Keep each name to 40 characters or fewer.
- Do not start an event name with a reserved prefix:
firebase_,google_, orga_. - Names are case-sensitive, so
Signupandsignupcount as two different events. - A property tracks up to 500 distinct event names.
- Each event accepts up to 25 parameters.
> Limits and reserved prefixes can change. Check Google's current documentation before a large rollout.
Deciding which kind of event to use
Check these options in order:
- If an automatic or enhanced measurement event already captures the interaction, use it.
- If a recommended event describes the interaction, use its name and parameters.
- Otherwise, create a custom event.
| Measurement need | Event type | Example name |
|---|---|---|
| Page loaded | Automatic | `page_view` |
| User completed login | Recommended | `login` |
| Newsletter signup button clicked | Custom | `newsletter_signup_click` |
Implementing events with gtag.js
Your data stream's gtag.js snippet must already be on the page. The following example sends a custom event when a visitor clicks a button:
<button id="signup">Subscribe</button>
<script>
document.getElementById('signup').addEventListener('click', function () {
gtag('event', 'newsletter_signup_click', {
placement: 'footer',
plan_type: 'free'
});
});
</script>The first argument to gtag('event', ...) is the event name. Each key in the object that follows is a parameter name, and its value is the parameter value.
:::note Parameters such as placement and plan_type appear in standard reports only after you register them as custom dimensions. Later chapters cover that step. :::
Exercise
Exercise
A developer wants to track when a visitor starts a free trial. No recommended event covers this. Which event type should they use, and what is a valid name?
Show answer
A custom event. A valid name is startfreetrial. It uses lowercase letters and underscores, is under 40 characters, and does not start with a reserved prefix.