How to send a custom GA4 event without using Tag Manager
Marc CastlesHaving the ability to view what users are doing on your website is very useful. It will help you make decisions on what is and isn’t working. Google Analytics 4 has lot of built in events that allow you to view details about what users are doing on your website. For example: page views. It also has lots of recommended events that you can trigger when appropriate, however you might want to track something that doesn’t really fit into the default events. This is when you will want to send a custom event.
Most guides recommend using Google Tag Manager to send custom events to Google Analytics. This is not one of those guides. For our website we don’t need all the bells and whistles that Tag Manager includes and I like to have complete control of the website markup. I have written this article mainly for “future me” to refer to but hopefully it can help you as well.
This is how to send a custom event in Google Analytics 4:
1. Use GTAG Google Analytics embed code
Make sure you are using the gtag embed code in your page HTML. Not the Tag Manager code because you won’t have the right Javascript function available. Your embed code should look like this:
<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>
The eagle eyed might notice that tagmanager is mentioned in the script src. This doesn’t mean that we are using tag manager, it just means that the gtag javascript is being served from that domain.
2. Call Javascript Event
When you want a custom event to be sent call the following javascript function at the appropriate time:
gtag("event", "my_custom_event");
Note. Google recommends event names written in snake_case
It is also possible to pass custom parameters as an object like this:
gtag("event", "my_custom_event", { "custom_param": "custom_param_value" });
3. Create custom dimensions in Google Analytics
If you are passing custom parameters then you will want to add the parameters into Google Analytics as custom dimensions so that you can view them when viewing the event details.
- In Google Analytics go to Admin > Data display > Custom dimensions
- Click the Create custom dimension button
- Enter an Dimension name. Make sure that Event scope is selected.
- Select your Event parameter name from the list if it exists or manually type it in.
- Click Save
Once you create the custom dimensions and the data starts flowing a card will show up when inspecting the event. It will look something like this: