-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrack-pageview.ts
More file actions
97 lines (84 loc) · 2.49 KB
/
track-pageview.ts
File metadata and controls
97 lines (84 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { parseHeaders } from "../server/headers";
import type {
AnalyticsPageview,
ServerContext,
TrackingOptions,
} from "../server/interfaces";
import {
isBuildTime,
isDoNotTrackEnabled,
isProduction,
parseRequest,
isEnhancedBotDetectionEnabled,
} from "../server/utils";
import { parseUtmParameters } from "../server/utm";
import { isValidPageview } from "./routes";
type TrackPageviewOptions = TrackingOptions & ServerContext;
export async function trackPageview(options: TrackPageviewOptions) {
const hostname = options.hostname ?? process.env.SIMPLE_ANALYTICS_HOSTNAME;
if (!hostname) {
console.error("No hostname provided for Simple Analytics");
return;
}
// We don't record non-GET requests
if ("request" in options && options.request.method !== "GET") {
return;
}
const { path, searchParams } =
"path" in options ? options : parseRequest(options.request);
const headers =
"headers" in options ? options.headers : options.request.headers;
// We don't record non-navigation requests
if (headers.get("Sec-Fetch-Mode") !== "navigate") {
return;
}
if (isDoNotTrackEnabled(headers) && !options.collectDnt) {
console.log("Do not track enabled, not tracking pageview");
return;
}
if (isBuildTime()) {
return;
}
if (!isProduction()) {
console.log(
"Simple Analytics is disabled by default in development and preview environments, enable it by setting ENABLE_ANALYTICS_IN_DEV=1 in your environment",
);
return;
}
if (!(await isValidPageview(path))) {
return;
}
const payload: AnalyticsPageview = {
type: "pageview",
hostname,
event: "pageview",
path,
...parseHeaders(headers, options.ignoreMetrics),
...(searchParams && !options.ignoreMetrics?.utm
? parseUtmParameters(searchParams, {
strictUtm: options.strictUtm ?? true,
})
: {}),
};
const response = await fetch("https://queue.simpleanalyticscdn.com/events", {
method: "POST",
headers: {
"Content-Type": "application/json",
...(headers.has("X-Forwarded-For") &&
isEnhancedBotDetectionEnabled(options) && {
"X-Forwarded-For": headers.get("X-Forwarded-For")!,
}),
},
body: JSON.stringify(payload),
});
if (!response.ok) {
try {
console.error(
`Failed to track pageview: ${response.status}`,
await response.json(),
);
} catch (error) {
console.error(`Failed to track pageview: ${response.status}`);
}
}
}