0.17.0

Analytics

Source code

Components for integrating analytics services like Google Analytics and Google Tag Manager into your Astro site.

AnalyticsGoogle

Integrates Google Analytics 4 (GA4) into your site.

Basic Usage

---
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:

With Partytown

Use Partytown to run analytics in a web worker for better performance:

<AnalyticsGoogle id="G-XXXXXXXXXX" partytown />

Props

PropTypeDefaultDescription
idstring"GA_MEASUREMENT_ID"Google Analytics Measurement ID (G-XXXXXXXXXX)
partytownbooleanfalseRun script in web worker via Partytown
requireConsentbooleanfalseWait for cookie consent before loading

AnalyticsGTM

Integrates Google Tag Manager.

Usage

---
import { AnalyticsGTM, AnalyticsGTMBody } from '@yatoday/astro-ui/astro';
---

<head>
  <AnalyticsGTM id="GTM-XXXXXXX" />
</head>

<body>
  <AnalyticsGTMBody id="GTM-XXXXXXX" />
  <!-- rest of body -->
</body>

Props

PropTypeDefaultDescription
idstring-Google Tag Manager Container ID (GTM-XXXXXXX)

Analytics (Auto-configured)

The Analytics component automatically loads analytics based on your config.yaml vendor configuration.

Usage

---
import { Analytics } from '@yatoday/astro-ui/astro';
---

<head>
  <Analytics />
</head>

Configuration

In your config.yaml:

analytics:
  vendors:
    googleAnalytics:
      id: "G-XXXXXXXXXX"
      partytown: false
    googleTagManager:
      id: "GTM-XXXXXXX"

Events

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');
});