From dab41abb1b57d1e53d7b80ff2d26bb506e73a4d1 Mon Sep 17 00:00:00 2001 From: Tomasz Subik Date: Mon, 25 Nov 2024 12:31:12 +0100 Subject: [PATCH] report web-vitals to GA --- components/layout/web-vitals-tracking.js | 18 ++++++++++++++++++ hooks/use-report-web-vitals.js | 21 +++++++++++++++++++++ pages/_app.js | 2 ++ 3 files changed, 41 insertions(+) create mode 100644 components/layout/web-vitals-tracking.js create mode 100644 hooks/use-report-web-vitals.js diff --git a/components/layout/web-vitals-tracking.js b/components/layout/web-vitals-tracking.js new file mode 100644 index 00000000..ddf84b44 --- /dev/null +++ b/components/layout/web-vitals-tracking.js @@ -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; +} diff --git a/hooks/use-report-web-vitals.js b/hooks/use-report-web-vitals.js new file mode 100644 index 00000000..523a854f --- /dev/null +++ b/hooks/use-report-web-vitals.js @@ -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]) +} diff --git a/pages/_app.js b/pages/_app.js index 663a34fd..a0566cd0 100644 --- a/pages/_app.js +++ b/pages/_app.js @@ -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 @@ -164,6 +165,7 @@ class MyApp extends App { > <> +