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 25, 2024
1 parent 258d414 commit 41a2685
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 1 deletion.
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";

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;
}
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
11 changes: 10 additions & 1 deletion pages/_document.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,16 @@ class MyDocument extends Document {
render() {
return (
<Html lang={this.props.language}>
<Head />
<Head>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
`
}}
/>
</Head>
<body>
{process.env.OSANO_ID && <Script src={`https://cmp.osano.com/${process.env.OSANO_ID}/osano.js`} strategy="beforeInteractive" />}
<GoogleTagManager noscript />
Expand Down

0 comments on commit 41a2685

Please sign in to comment.