Add Google Analytics to Next.js App
Here is an example Google analytics component which uses Next/Script https://nextjs.org/docs/basic-features/script
const isProduction = process.env.NODE_ENV === 'production'
import Script from 'next/script'
const GA = () => {
return (
<>
<Script
strategy="lazyOnload"
src={`https://www.googletagmanager.com/gtag/js?id=YOUR_GA_CODE`}
/>
<Script strategy="lazyOnload">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'YOUR_GA_CODE', {
page_path: window.location.pathname,
});
`}
</Script>
</>
)
}
// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const logEvent = (action, category, label, value) => {
window.gtag?.('event', action, {
event_category: category,
event_label: label,
value: value,
})
}
const Analytics = () => isProduction && <GA />
export default Analytics
Use within _app.js component
.....
</head>
<GA/>
....
..