@vulcantech/analytics 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +111 -0
- package/dist/index.d.mts +39 -0
- package/dist/index.d.ts +39 -0
- package/dist/index.js +162 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +153 -0
- package/dist/index.mjs.map +1 -0
- package/dist/route.d.mts +19 -0
- package/dist/route.d.ts +19 -0
- package/dist/route.js +61 -0
- package/dist/route.js.map +1 -0
- package/dist/route.mjs +58 -0
- package/dist/route.mjs.map +1 -0
- package/dist/tags.d.mts +58 -0
- package/dist/tags.d.ts +58 -0
- package/dist/tags.js +94 -0
- package/dist/tags.js.map +1 -0
- package/dist/tags.mjs +87 -0
- package/dist/tags.mjs.map +1 -0
- package/package.json +69 -0
- package/src/AnalyticsTracker.tsx +45 -0
- package/src/index.tsx +12 -0
- package/src/route.ts +85 -0
- package/src/tags.tsx +167 -0
- package/src/tracker.ts +191 -0
package/src/tags.tsx
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CMS-driven third-party tracking-tag injection (server-side).
|
|
3
|
+
*
|
|
4
|
+
* Fetches tag IDs (GA4 / Google Ads / Meta Pixel) configured for this
|
|
5
|
+
* project in vulcantech-cms and renders the corresponding third-party
|
|
6
|
+
* <Script> loaders — giving consumer sites "codeless" tag setup with no
|
|
7
|
+
* hand-rolled gtag/fbq wiring in their own layout.
|
|
8
|
+
*
|
|
9
|
+
* This module is a React Server Component — do NOT add "use client".
|
|
10
|
+
*
|
|
11
|
+
* Required env vars:
|
|
12
|
+
* VULCANTECH_CMS_URL — CMS base URL (defaults to https://cms.vulcantech.io)
|
|
13
|
+
* VULCANTECH_PROJECT_ID — project ID for this site
|
|
14
|
+
* VULCANTECH_API_KEY — API key for this site (needs the analytics:read scope)
|
|
15
|
+
*
|
|
16
|
+
* Optional env fallbacks (used only when the CMS omits a field):
|
|
17
|
+
* NEXT_PUBLIC_GA_ID → ga4Id
|
|
18
|
+
* NEXT_PUBLIC_GOOGLE_ADS_ID → googleAdsId
|
|
19
|
+
* NEXT_PUBLIC_META_PIXEL_ID → metaPixelId
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import Script from "next/script";
|
|
23
|
+
|
|
24
|
+
/** Tracking tag IDs resolved for a project (CMS value wins, else env fallback). */
|
|
25
|
+
export interface TrackingTags {
|
|
26
|
+
/** GA4 measurement ID, e.g. "G-XXXXXXXXXX". */
|
|
27
|
+
ga4Id?: string;
|
|
28
|
+
/** Google Ads conversion ID, e.g. "AW-XXXXXXXXX". */
|
|
29
|
+
googleAdsId?: string;
|
|
30
|
+
/** Meta (Facebook) Pixel ID. */
|
|
31
|
+
metaPixelId?: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Shape returned by GET {CMS_URL}/api/analytics/config. */
|
|
35
|
+
interface ConfigResponse {
|
|
36
|
+
config: TrackingTags | null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* fetch init with Next's ISR options. Passed as a typed variable (not an
|
|
41
|
+
* object literal) so TS won't excess-property-check the `next` key — this
|
|
42
|
+
* package doesn't load Next's global RequestInit augmentation. Mirrors the
|
|
43
|
+
* collections/blog packages.
|
|
44
|
+
*/
|
|
45
|
+
type IsrFetchInit = RequestInit & {
|
|
46
|
+
next?: { revalidate?: number; tags?: string[] };
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Fetch the tracking-tag config for this project from the CMS, merging in
|
|
51
|
+
* env fallbacks per field (CMS value wins when present).
|
|
52
|
+
*
|
|
53
|
+
* Never throws — tags must never break a page build. Returns `null` when
|
|
54
|
+
* all three tag IDs end up empty (nothing configured anywhere), otherwise a
|
|
55
|
+
* {@link TrackingTags} object.
|
|
56
|
+
*
|
|
57
|
+
* The fetch is ISR-cached (`revalidate: 60`) and tagged
|
|
58
|
+
* `tracking-tags:{projectId}` so the CMS can purge it on config change.
|
|
59
|
+
*/
|
|
60
|
+
export async function fetchTrackingTags(): Promise<TrackingTags | null> {
|
|
61
|
+
const CMS_URL = process.env.VULCANTECH_CMS_URL || "https://cms.vulcantech.io";
|
|
62
|
+
const PROJECT_ID = process.env.VULCANTECH_PROJECT_ID;
|
|
63
|
+
const API_KEY = process.env.VULCANTECH_API_KEY;
|
|
64
|
+
|
|
65
|
+
let cms: TrackingTags | null = null;
|
|
66
|
+
|
|
67
|
+
if (PROJECT_ID && API_KEY) {
|
|
68
|
+
try {
|
|
69
|
+
const params = new URLSearchParams({
|
|
70
|
+
projectId: PROJECT_ID,
|
|
71
|
+
apiKey: API_KEY,
|
|
72
|
+
});
|
|
73
|
+
const init: IsrFetchInit = {
|
|
74
|
+
next: { revalidate: 60, tags: [`tracking-tags:${PROJECT_ID}`] },
|
|
75
|
+
};
|
|
76
|
+
const res = await fetch(`${CMS_URL}/api/analytics/config?${params}`, init);
|
|
77
|
+
if (res.ok) {
|
|
78
|
+
const json = (await res.json()) as ConfigResponse;
|
|
79
|
+
cms = json.config ?? null;
|
|
80
|
+
}
|
|
81
|
+
} catch {
|
|
82
|
+
// Silent fail — fall through to env fallbacks below.
|
|
83
|
+
cms = null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// CMS value wins per field; fill any gap from public env vars.
|
|
88
|
+
const merged: TrackingTags = {
|
|
89
|
+
ga4Id: cms?.ga4Id || process.env.NEXT_PUBLIC_GA_ID || undefined,
|
|
90
|
+
googleAdsId:
|
|
91
|
+
cms?.googleAdsId || process.env.NEXT_PUBLIC_GOOGLE_ADS_ID || undefined,
|
|
92
|
+
metaPixelId:
|
|
93
|
+
cms?.metaPixelId || process.env.NEXT_PUBLIC_META_PIXEL_ID || undefined,
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
if (!merged.ga4Id && !merged.googleAdsId && !merged.metaPixelId) {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
return merged;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Drop-in server component that injects the project's tracking tags.
|
|
104
|
+
*
|
|
105
|
+
* Place once in your root layout's `<body>`:
|
|
106
|
+
*
|
|
107
|
+
* import { CMSTags } from "@vulcantech/analytics/tags";
|
|
108
|
+
* // <body> ... <CMSTags /> ... </body>
|
|
109
|
+
*
|
|
110
|
+
* Renders one shared gtag.js loader + init (config'd for every present
|
|
111
|
+
* Google ID: GA4 and/or Google Ads), the standard Meta Pixel bootstrap +
|
|
112
|
+
* <noscript> fallback, or `null` when nothing is configured.
|
|
113
|
+
*/
|
|
114
|
+
export async function CMSTags() {
|
|
115
|
+
const tags = await fetchTrackingTags();
|
|
116
|
+
if (!tags) return null;
|
|
117
|
+
|
|
118
|
+
const { ga4Id, googleAdsId, metaPixelId } = tags;
|
|
119
|
+
const googleIds = [ga4Id, googleAdsId].filter(Boolean) as string[];
|
|
120
|
+
const firstGoogleId = googleIds[0];
|
|
121
|
+
|
|
122
|
+
return (
|
|
123
|
+
<>
|
|
124
|
+
{firstGoogleId && (
|
|
125
|
+
<>
|
|
126
|
+
<Script
|
|
127
|
+
id="vt-gtag"
|
|
128
|
+
async
|
|
129
|
+
src={`https://www.googletagmanager.com/gtag/js?id=${firstGoogleId}`}
|
|
130
|
+
strategy="afterInteractive"
|
|
131
|
+
/>
|
|
132
|
+
<Script id="vt-gtag-init" strategy="afterInteractive">
|
|
133
|
+
{`window.dataLayer = window.dataLayer || [];
|
|
134
|
+
function gtag(){dataLayer.push(arguments);}
|
|
135
|
+
gtag('js', new Date());
|
|
136
|
+
${googleIds.map((id) => `gtag('config', '${id}');`).join("\n")}`}
|
|
137
|
+
</Script>
|
|
138
|
+
</>
|
|
139
|
+
)}
|
|
140
|
+
{metaPixelId && (
|
|
141
|
+
<>
|
|
142
|
+
<Script id="vt-meta-pixel" strategy="afterInteractive">
|
|
143
|
+
{`!function(f,b,e,v,n,t,s)
|
|
144
|
+
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
|
|
145
|
+
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
|
|
146
|
+
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
|
|
147
|
+
n.queue=[];t=b.createElement(e);t.async=!0;
|
|
148
|
+
t.src=v;s=b.getElementsByTagName(e)[0];
|
|
149
|
+
s.parentNode.insertBefore(t,s)}(window, document,'script',
|
|
150
|
+
'https://connect.facebook.net/en_US/fbevents.js');
|
|
151
|
+
fbq('init', '${metaPixelId}');
|
|
152
|
+
fbq('track', 'PageView');`}
|
|
153
|
+
</Script>
|
|
154
|
+
<noscript>
|
|
155
|
+
<img
|
|
156
|
+
height="1"
|
|
157
|
+
width="1"
|
|
158
|
+
style={{ display: "none" }}
|
|
159
|
+
src={`https://www.facebook.com/tr?id=${metaPixelId}&ev=PageView&noscript=1`}
|
|
160
|
+
alt=""
|
|
161
|
+
/>
|
|
162
|
+
</noscript>
|
|
163
|
+
</>
|
|
164
|
+
)}
|
|
165
|
+
</>
|
|
166
|
+
);
|
|
167
|
+
}
|
package/src/tracker.ts
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* VulcanTech Analytics — lightweight first-party tracker.
|
|
3
|
+
*
|
|
4
|
+
* < 1KB gzipped. No cookies, no fingerprinting, no DOM manipulation.
|
|
5
|
+
* Sends page views and custom events to /api/a on the same domain
|
|
6
|
+
* via navigator.sendBeacon (falls back to fetch).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const ENDPOINT = "/api/a";
|
|
10
|
+
const SESSION_KEY = "__vt_sid";
|
|
11
|
+
|
|
12
|
+
/** Generate a random session ID (stored in sessionStorage, not cookies). */
|
|
13
|
+
function getSessionId(): string {
|
|
14
|
+
if (typeof window === "undefined") return "";
|
|
15
|
+
try {
|
|
16
|
+
let sid = sessionStorage.getItem(SESSION_KEY);
|
|
17
|
+
if (!sid) {
|
|
18
|
+
sid = Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
19
|
+
sessionStorage.setItem(SESSION_KEY, sid);
|
|
20
|
+
}
|
|
21
|
+
return sid;
|
|
22
|
+
} catch {
|
|
23
|
+
return Math.random().toString(36).slice(2);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Extract UTM params from the current URL. */
|
|
28
|
+
function getUtmParams(): Record<string, string> {
|
|
29
|
+
if (typeof window === "undefined") return {};
|
|
30
|
+
const params = new URLSearchParams(window.location.search);
|
|
31
|
+
const utms: Record<string, string> = {};
|
|
32
|
+
for (const key of [
|
|
33
|
+
"utm_source",
|
|
34
|
+
"utm_medium",
|
|
35
|
+
"utm_campaign",
|
|
36
|
+
"utm_term",
|
|
37
|
+
"utm_content",
|
|
38
|
+
]) {
|
|
39
|
+
const val = params.get(key);
|
|
40
|
+
if (val) utms[key] = val;
|
|
41
|
+
}
|
|
42
|
+
return utms;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface AnalyticsEvent {
|
|
46
|
+
type: "pageview" | "event";
|
|
47
|
+
url: string;
|
|
48
|
+
ref: string;
|
|
49
|
+
sid: string;
|
|
50
|
+
vw: number;
|
|
51
|
+
vh: number;
|
|
52
|
+
ts: number;
|
|
53
|
+
utm?: Record<string, string>;
|
|
54
|
+
name?: string;
|
|
55
|
+
props?: Record<string, string | number | boolean>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Check if we're in a dev environment — skip all tracking if so. */
|
|
59
|
+
function isDev(): boolean {
|
|
60
|
+
if (typeof window === "undefined") return true;
|
|
61
|
+
const host = window.location.hostname;
|
|
62
|
+
return (
|
|
63
|
+
host === "localhost" ||
|
|
64
|
+
host === "127.0.0.1" ||
|
|
65
|
+
host === "0.0.0.0" ||
|
|
66
|
+
host.endsWith(".local") ||
|
|
67
|
+
host.includes("localhost")
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Send an analytics event via beacon (non-blocking). */
|
|
72
|
+
function send(event: AnalyticsEvent): void {
|
|
73
|
+
if (isDev()) return;
|
|
74
|
+
const payload = JSON.stringify(event);
|
|
75
|
+
try {
|
|
76
|
+
if (navigator.sendBeacon) {
|
|
77
|
+
navigator.sendBeacon(ENDPOINT, payload);
|
|
78
|
+
} else {
|
|
79
|
+
fetch(ENDPOINT, {
|
|
80
|
+
method: "POST",
|
|
81
|
+
body: payload,
|
|
82
|
+
headers: { "Content-Type": "application/json" },
|
|
83
|
+
keepalive: true,
|
|
84
|
+
}).catch(() => {});
|
|
85
|
+
}
|
|
86
|
+
} catch {
|
|
87
|
+
// Silently fail — analytics should never break the app
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Track a page view. */
|
|
92
|
+
export function trackPageView(): void {
|
|
93
|
+
if (typeof window === "undefined") return;
|
|
94
|
+
const utms = getUtmParams();
|
|
95
|
+
send({
|
|
96
|
+
type: "pageview",
|
|
97
|
+
url: window.location.pathname + window.location.search,
|
|
98
|
+
ref: document.referrer,
|
|
99
|
+
sid: getSessionId(),
|
|
100
|
+
vw: window.innerWidth,
|
|
101
|
+
vh: window.innerHeight,
|
|
102
|
+
ts: Date.now(),
|
|
103
|
+
...(Object.keys(utms).length > 0 ? { utm: utms } : {}),
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Track a custom event. */
|
|
108
|
+
export function trackEvent(
|
|
109
|
+
name: string,
|
|
110
|
+
props?: Record<string, string | number | boolean>,
|
|
111
|
+
): void {
|
|
112
|
+
if (typeof window === "undefined") return;
|
|
113
|
+
send({
|
|
114
|
+
type: "event",
|
|
115
|
+
url: window.location.pathname,
|
|
116
|
+
ref: "",
|
|
117
|
+
sid: getSessionId(),
|
|
118
|
+
vw: window.innerWidth,
|
|
119
|
+
vh: window.innerHeight,
|
|
120
|
+
ts: Date.now(),
|
|
121
|
+
name,
|
|
122
|
+
props,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Track when a form comes into view. */
|
|
127
|
+
export function trackFormView(formId: string, formName?: string): void {
|
|
128
|
+
trackEvent("form_view", { formId, formName: formName ?? "" });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Track when a form is submitted successfully. */
|
|
132
|
+
export function trackFormSubmit(
|
|
133
|
+
formId: string,
|
|
134
|
+
formName?: string,
|
|
135
|
+
submissionType?: string,
|
|
136
|
+
): void {
|
|
137
|
+
trackEvent("form_submit", {
|
|
138
|
+
formId,
|
|
139
|
+
formName: formName ?? "",
|
|
140
|
+
submissionType: submissionType ?? "contact",
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Track when a phone number link is clicked. */
|
|
145
|
+
export function trackPhoneClick(phoneNumber?: string): void {
|
|
146
|
+
trackEvent("phone_click", { phone: phoneNumber ?? "" });
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Track when an email link is clicked. */
|
|
150
|
+
export function trackEmailClick(email?: string): void {
|
|
151
|
+
trackEvent("email_click", { email: email ?? "" });
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Track a 404 page. */
|
|
155
|
+
export function track404(url?: string): void {
|
|
156
|
+
trackEvent("404", { url: url ?? window?.location?.pathname ?? "" });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/* ------------------------------------------------------------------ */
|
|
160
|
+
/* Global hook registration */
|
|
161
|
+
/* ------------------------------------------------------------------ */
|
|
162
|
+
|
|
163
|
+
// Expose the conversion trackers on a window global so UI packages
|
|
164
|
+
// (e.g. @vulcantech/forms) can report form views/submits without a
|
|
165
|
+
// hard dependency on this module, and install ONE delegated click
|
|
166
|
+
// listener so tel:/mailto: links track phone/email conversions on
|
|
167
|
+
// every page with zero per-component wiring.
|
|
168
|
+
if (typeof window !== "undefined") {
|
|
169
|
+
const w = window as unknown as Record<string, unknown>;
|
|
170
|
+
w.__vtTrack = {
|
|
171
|
+
trackFormView,
|
|
172
|
+
trackFormSubmit,
|
|
173
|
+
trackPhoneClick,
|
|
174
|
+
trackEmailClick,
|
|
175
|
+
};
|
|
176
|
+
if (!w.__vtClickTrackingInstalled) {
|
|
177
|
+
w.__vtClickTrackingInstalled = true;
|
|
178
|
+
document.addEventListener(
|
|
179
|
+
"click",
|
|
180
|
+
(e) => {
|
|
181
|
+
const target = e.target as Element | null;
|
|
182
|
+
const link = target?.closest?.("a[href^='tel:'], a[href^='mailto:']");
|
|
183
|
+
if (!link) return;
|
|
184
|
+
const href = link.getAttribute("href") || "";
|
|
185
|
+
if (href.startsWith("tel:")) trackPhoneClick(href.slice(4));
|
|
186
|
+
else trackEmailClick(href.slice(7));
|
|
187
|
+
},
|
|
188
|
+
true,
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
}
|