Google Analytics
Like the Sentry integration, the Google Analytics integration is ready to go.
Prerequisites
- A Google Analytics account
Setup
There is a script at the bottom of the ./app/root.tsx
file that adds the Google Tag Manager script to the page.
To enable it, the VITE_GOOGLE_TAG_ID
environment variable needs to be set.
VITE_GOOGLE_TAG_ID=""
You can get the Google Tag ID after creating a Google Analytics account and project.
Google Analytics vs. Google Tag Manager
As you will see in ./app/root.tsx
, the script does not add Google Analytics per se, but it adds Google Tag Manager.
Google Tag Manager is a tool that allows you to manage your website's tags, a tag is a snippet of code.
Google Analytics has its own tag, Google Ads has another tag, for example.
If, let's say, you wanted to enable Google Ads, rather than changing the code in your website, you would just add the Google Ads tag to the Google Tag Manager and that will enable the tag in your website.
Sending events to Google Analytics
Sending events to Google Analytics is useful because it allows you to track user behavior on your website.
For example, you can track button clicks, form submissions, and more.
To send events to Google Analytics, you can use the trackEvent
function located in `./app/core/lib/analytics.client.ts
export default function trackEvent<T extends string>(
eventName: T,
properties?: Record<string, unknown>,
) {
return window.gtag && window.gtag('event', eventName, properties)
}
To use this function, you can do the following, for example:
import { trackEvent } from '@/core/lib/analytics.client'
export function Button() {
return (
<button
onClick={() => trackEvent('button_clicked', { button_name: 'Login' })}
>
Login
</button>
)
}
Debugging Integration
To debug the Google Analytics integration, you can go to the /debug/analytics
page.
There is a button to trigger a test event.
Once clicked, if you head to your Google Analytics account > Reports > Realtime overview, you should see the test event show up.
Delete in production
The /debug/analytics
page should be deleted / hidden in production, it is for you to use it as a testing page.