Skip to content

Instantly share code, notes, and snippets.

@harshmaur
Created October 29, 2022 06:44
Show Gist options
  • Save harshmaur/0b21b0ec4c49ff63a034855699c06629 to your computer and use it in GitHub Desktop.
Save harshmaur/0b21b0ec4c49ff63a034855699c06629 to your computer and use it in GitHub Desktop.
GA Tracking _app.tsx
import App, { NextWebVitalsMetric } from 'next/app'
import '../styles/globals.css'
import type { AppProps, AppContext } from 'next/app'
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function MyApp({ Component, pageProps }: AppProps) {
return (
<Component {…pageProps} />
)
}
MyApp.getInitialProps = async (appContext: AppContext) => {
// calls page's `getInitialProps` and fills `appProps.pageProps`
const appProps = await App.getInitialProps(appContext)
return { …appProps }
}
export function reportWebVitals({ id, name, label, value, }: NextWebVitalsMetric): void {
window.gtag('event', name, {
event_category: label === 'web-vital' ? 'Web Vitals' : 'Next.js custom metric',
value: Math.round(name === 'CLS' ? value * 1000 : value), // values must be integers
event_label: id, // id unique to current page load
non_interaction: true, // avoids affecting bounce rate.
})
}
export default MyApp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment