/
analytics.tsx
141 lines (122 loc) · 3.34 KB
/
analytics.tsx
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import Cookies from 'js-cookie';
import { useEffect } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { useAppContext } from './contexts/appContext';
const GA_TRACKING_ID = 'G-72XG3F8LNJ'; // This is Hashnode's GA tracking ID
const isProd = process.env.NEXT_PUBLIC_MODE === 'production';
const BASE_PATH = process.env.NEXT_PUBLIC_BASE_URL || '';
export const Analytics = () => {
const { publication, post, series, page } = useAppContext();
const _sendPageViewsToHashnodeGoogleAnalytics = () => {
// @ts-ignore
window.gtag('config', GA_TRACKING_ID, {
transport_url: 'https://ping.hashnode.com',
first_party_collection: true,
});
};
const _sendViewsToHashnodeInternalAnalytics = async () => {
// Send to Hashnode's own internal analytics
const event: Record<string, string | number | object> = {
event_type: 'pageview',
time: new Date().getTime(),
event_properties: {
hostname: window.location.hostname,
url: window.location.pathname,
eventType: 'pageview',
publicationId: publication.id,
dateAdded: new Date().getTime(),
referrer: window.document.referrer,
},
};
let deviceId = Cookies.get('__amplitudeDeviceID');
if (!deviceId) {
deviceId = uuidv4();
Cookies.set('__amplitudeDeviceID', deviceId, {
expires: 365 * 2,
}); // expire after two years
}
event['device_id'] = deviceId;
await fetch(`${BASE_PATH}/ping/data-event`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ events: [event] }),
});
};
function _sendViewsToAdvancedAnalyticsDashboard() {
const publicationId = publication.id;
const postId = post && post.id;
const seriesId = series?.id || post?.series?.id;
const staticPageId = page && page.id;
const data = {
publicationId,
postId,
seriesId,
staticPageId,
};
if (!publicationId) {
console.warn('Publication ID is missing; could not send analytics.');
return;
}
const isBrowser = typeof window !== 'undefined';
if (!isBrowser) {
return;
}
const isLocalhost = window.location.hostname === 'localhost';
if (isLocalhost) {
console.warn(
'Analytics API call is skipped because you are running on localhost; data:',
data,
);
return;
}
const event = {
// timestamp will be added in API
payload: {
publicationId,
postId: postId || null,
seriesId: seriesId || null,
pageId: staticPageId || null,
url: window.location.href,
referrer: document.referrer || null,
language: navigator.language || null,
screen: `${window.screen.width}x${window.screen.height}`,
},
type: 'pageview',
};
const blob = new Blob(
[
JSON.stringify({
events: [event],
}),
],
{
type: 'application/json; charset=UTF-8',
},
);
let hasSentBeacon = false;
try {
if (navigator.sendBeacon) {
hasSentBeacon = navigator.sendBeacon(`${BASE_PATH}/api/analytics`, blob);
}
} catch (error) {
// do nothing; in case there is an error we fall back to fetch
}
if (!hasSentBeacon) {
fetch(`${BASE_PATH}/api/analytics`, {
method: 'POST',
body: blob,
credentials: 'omit',
keepalive: true,
});
}
}
useEffect(() => {
if (!isProd) return;
_sendPageViewsToHashnodeGoogleAnalytics();
_sendViewsToHashnodeInternalAnalytics();
_sendViewsToAdvancedAnalyticsDashboard();
}, []);
return null;
};