Skip to content

Commit e8de0b4

Browse files
authored
feat: send web vitals metrics to GA (#435)
1 parent 142ec87 commit e8de0b4

File tree

4 files changed

+57
-0
lines changed

4 files changed

+57
-0
lines changed

package-lock.json

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
"unist-util-visit": "^4.1.2",
5454
"url": "^0.11.0",
5555
"uuid": "^10.0.0",
56+
"web-vitals": "^5.1.0",
5657
"yaml": "^2.8.0"
5758
},
5859
"devDependencies": {

src/hooks/useReportWebVitals.tsx

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import {useEffect} from 'react';
2+
import {type Metric, onCLS, onFCP, onINP, onLCP, onTTFB} from 'web-vitals';
3+
4+
import {IS_PRODUCTION} from '../constants';
5+
6+
declare global {
7+
interface Window {
8+
dataLayer?: any[];
9+
}
10+
}
11+
12+
const sendToGoogleAnalytics = (metric: Metric) => {
13+
if (typeof window !== 'undefined') {
14+
if (!IS_PRODUCTION) {
15+
console.info(`[Web Vitals] ${metric.name}: ${metric.value}`);
16+
return;
17+
}
18+
19+
if (window.dataLayer) {
20+
window.dataLayer = window.dataLayer || [];
21+
window.dataLayer.push({
22+
event: 'web-vitals',
23+
event_category: 'Web Vitals',
24+
event_action: metric.name,
25+
event_label: metric.id,
26+
event_value: metric.value,
27+
non_interaction: true,
28+
});
29+
}
30+
}
31+
};
32+
33+
const reportWebVitals = (): void => {
34+
// Core Web Vitals
35+
onCLS((data) => sendToGoogleAnalytics(data));
36+
onLCP((data) => sendToGoogleAnalytics(data));
37+
38+
// Others metriks
39+
onINP((data) => sendToGoogleAnalytics(data));
40+
onFCP((data) => sendToGoogleAnalytics(data));
41+
onTTFB((data) => sendToGoogleAnalytics(data));
42+
};
43+
44+
export const useReportWebVitals = () => {
45+
return useEffect(() => {
46+
reportWebVitals();
47+
}, []);
48+
};

src/pages/_app.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {NextComponentType} from 'next';
44
import {appWithTranslation} from 'next-i18next';
55
import 'prismjs/themes/prism-tomorrow.min.css';
66

7+
import {useReportWebVitals} from '../hooks/useReportWebVitals';
78
import '../styles.scss';
89
import '../vendors.scss';
910

@@ -14,6 +15,7 @@ export const App = ({
1415
Component: NextComponentType;
1516
pageProps: Record<string, unknown>;
1617
}) => {
18+
useReportWebVitals();
1719
return <Component {...pageProps} />;
1820
};
1921

0 commit comments

Comments
 (0)