Skip to content

Commit

Permalink
report web-vitals to GA
Browse files Browse the repository at this point in the history
  • Loading branch information
tsubik committed Nov 26, 2024
1 parent 258d414 commit dab41ab
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
18 changes: 18 additions & 0 deletions components/layout/web-vitals-tracking.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import useReportWebVitals from "hooks/use-report-web-vitals";
import { logEvent } from "utils/analytics";

function sendToGTM({name, delta, value, id}) {
logEvent('web_vitals', {
cwv_metric: name,
cwv_id: id,
cw_value: delta,
cwv_metric_value: value,
cwv_metric_delta: delta,
});
}

export function WebVitalsTracking() {
useReportWebVitals(sendToGTM);

return null;
}
21 changes: 21 additions & 0 deletions hooks/use-report-web-vitals.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useEffect } from 'react'
import {
onLCP,
onFID,
onCLS,
onINP,
onFCP,
onTTFB
} from 'next/dist/compiled/web-vitals'

// taken from newer nextjs version as 12 does not have it
export default function useReportWebVitals(reportWebVitalsFn) {
useEffect(() => {
onCLS(reportWebVitalsFn)
onFID(reportWebVitalsFn)
onLCP(reportWebVitalsFn)
onINP(reportWebVitalsFn)
onFCP(reportWebVitalsFn)
onTTFB(reportWebVitalsFn)
}, [reportWebVitalsFn])
}
2 changes: 2 additions & 0 deletions pages/_app.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import 'dayjs/locale/vi';
import 'dayjs/locale/zh-cn';

import 'css/index.scss';
import { WebVitalsTracking } from '~/components/layout/web-vitals-tracking';

const reducer = combineReducers({
...reducers
Expand Down Expand Up @@ -164,6 +165,7 @@ class MyApp extends App {
>
<Provider store={store}>
<>
<WebVitalsTracking />
<GoogleTagManager />
<PageViewTracking />
<Component {...pageProps} language={language} />
Expand Down

0 comments on commit dab41ab

Please sign in to comment.