diff --git a/components/layout/web-vitals-tracking.js b/components/layout/web-vitals-tracking.js new file mode 100644 index 00000000..f75f83cc --- /dev/null +++ b/components/layout/web-vitals-tracking.js @@ -0,0 +1,18 @@ +import useReportWebVitals from "hooks/use-report-web-vitals"; + +function sendToGoogleAnalytics({name, delta, value, id}) { + gtag('event', name, { + // Built-in params: + value: delta, // Use `delta` so the value can be summed. + // Custom params: + metric_id: id, // Needed to aggregate events. + metric_value: value, + metric_delta: delta, + }); +} + +export function WebVitalsTracking() { + useReportWebVitals(sendToGoogleAnalytics); + + 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 { > <> + diff --git a/pages/_document.js b/pages/_document.js index b5388a1c..a431670b 100644 --- a/pages/_document.js +++ b/pages/_document.js @@ -17,7 +17,16 @@ class MyDocument extends Document { render() { return ( - + +