Skip to content

Commit 1d11b21

Browse files
feat(analytics): add integration for external page entry tracking via Cloudflare Workers
1 parent b308ad5 commit 1d11b21

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

astro.config.mjs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// @ts-check
22
import { defineConfig } from "astro/config";
33
import starlight from "@astrojs/starlight";
4+
import { analytics } from "./src/integrations/analytics";
45

56
// https://astro.build/config
67
export default defineConfig({
@@ -36,6 +37,7 @@ export default defineConfig({
3637
"./src/styles/custom.css",
3738
],
3839
}),
40+
analytics(),
3941
],
4042
site: "https://keshav.is-a.dev",
4143
base: "FreqKnow",

src/integrations/analytics.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import type { AstroIntegration } from "astro";
2+
3+
export function analytics(): AstroIntegration {
4+
return {
5+
name: "analytics",
6+
hooks: {
7+
"astro:config:setup": ({ injectScript }) => {
8+
injectScript(
9+
"page",
10+
`
11+
const API_URL = "https://freq-know-analytics.dhimankeshav201.workers.dev/track/";
12+
13+
export function trackPageEntry() {
14+
// Don't track in development
15+
if (window.location.hostname === "localhost") return;
16+
17+
const referrer = document.referrer;
18+
const currentDomain = window.location.hostname;
19+
20+
// Check if referrer is from a different domain (or no referrer = direct visit)
21+
const isExternalEntry =
22+
!referrer || (referrer && new URL(referrer).hostname !== currentDomain);
23+
24+
if (isExternalEntry) {
25+
fetch(API_URL, {
26+
method: "GET",
27+
}).catch(() => {}); // Silent fail
28+
}
29+
}
30+
`,
31+
);
32+
},
33+
},
34+
};
35+
}

0 commit comments

Comments
 (0)