Skip to content

Commit 5314100

Browse files
committed
feat: integrate Google Analytics and update environment variable prefix to PUBLIC_
1 parent 1281f19 commit 5314100

3 files changed

Lines changed: 24 additions & 7 deletions

File tree

.env.example

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
1-
# .env
2-
VITE_GA_MEASUREMENT_ID=G-XXXXXXXXXX
1+
PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXXXX

src/components/BaseHead.astro

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,23 @@ const esURL = lang === 'es' ? canonicalURL.href : (alternateUrl ?? new URL('/es/
5555
<!-- Fonts -->
5656
<link rel="preconnect" href="https://fonts.googleapis.com" />
5757
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
58-
<link
59-
href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap"
60-
rel="stylesheet"
61-
/>
58+
59+
{
60+
import.meta.env.PUBLIC_GA_MEASUREMENT_ID && (
61+
<>
62+
<script
63+
is:inline
64+
async
65+
src={`https://www.googletagmanager.com/gtag/js?id=${import.meta.env.PUBLIC_GA_MEASUREMENT_ID}`}
66+
/>
67+
<script is:inline define:vars={{ id: import.meta.env.PUBLIC_GA_MEASUREMENT_ID }}>
68+
window.dataLayer = window.dataLayer || [];
69+
window.gtag = function () {
70+
window.dataLayer.push(arguments);
71+
};
72+
gtag('js', new Date());
73+
gtag('config', id);
74+
</script>
75+
</>
76+
)
77+
}

src/lib/analytics.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// src/lib/analytics.ts
22
// Utility for Google Analytics event tracking
33

4-
const GA_MEASUREMENT_ID = import.meta.env.VITE_GA_MEASUREMENT_ID;
4+
const GA_MEASUREMENT_ID = import.meta.env.PUBLIC_GA_MEASUREMENT_ID;
55

66
export function trackEvent({
77
action,
@@ -20,6 +20,8 @@ export function trackEvent({
2020
event_label: label,
2121
value: value,
2222
});
23+
} else if (import.meta.env.DEV) {
24+
console.log('[Analytics]', { action, category, label, value });
2325
}
2426
}
2527

0 commit comments

Comments
 (0)