Components for integrating analytics services like Google Analytics and Google Tag Manager into your Astro site.
Integrates Google Analytics 4 (GA4) into your site.
---
import { AnalyticsGoogle } from '@yatoday/astro-ui/astro';
---
<head>
<AnalyticsGoogle id="G-XXXXXXXXXX" />
</head>
Use the requireConsent prop to defer loading until the user accepts cookies. This requires the CookieConsent component to be present on the page.
---
import { AnalyticsGoogle, CookieConsent } from '@yatoday/astro-ui/astro';
---
<head>
<AnalyticsGoogle id="G-XXXXXXXXXX" requireConsent />
</head>
<body>
<CookieConsent
title="This website uses cookies"
description="We use cookies to analyze our traffic."
denyText="Deny"
allowText="Allow all"
/>
</body>
When requireConsent is enabled:
cookie-consent-analytics-enabled event (fired when user clicks “Allow all”)analytics-loaded event when GA is initializedUse Partytown to run analytics in a web worker for better performance:
<AnalyticsGoogle id="G-XXXXXXXXXX" partytown />
| Prop | Type | Default | Description |
|---|---|---|---|
id | string | "GA_MEASUREMENT_ID" | Google Analytics Measurement ID (G-XXXXXXXXXX) |
partytown | boolean | false | Run script in web worker via Partytown |
requireConsent | boolean | false | Wait for cookie consent before loading |
Integrates Google Tag Manager.
---
import { AnalyticsGTM, AnalyticsGTMBody } from '@yatoday/astro-ui/astro';
---
<head>
<AnalyticsGTM id="GTM-XXXXXXX" />
</head>
<body>
<AnalyticsGTMBody id="GTM-XXXXXXX" />
<!-- rest of body -->
</body>
| Prop | Type | Default | Description |
|---|---|---|---|
id | string | - | Google Tag Manager Container ID (GTM-XXXXXXX) |
The Analytics component automatically loads analytics based on your config.yaml vendor configuration.
---
import { Analytics } from '@yatoday/astro-ui/astro';
---
<head>
<Analytics />
</head>
In your config.yaml:
analytics:
vendors:
googleAnalytics:
id: "G-XXXXXXXXXX"
partytown: false
googleTagManager:
id: "GTM-XXXXXXX"
When using requireConsent, you can listen for these events:
// Analytics has been loaded and initialized
window.addEventListener('analytics-loaded', (e) => {
console.log('GA loaded with ID:', e.detail.id);
});
// Track custom events after consent
window.addEventListener('cookie-consent-analytics-enabled', () => {
// Safe to use gtag() here
gtag('event', 'page_view');
});