How to use google analytics with next.js app?

Answer

To correctly initialize gtag, do the following in _document.js or wherever you defined Head:

import { Head } from 'next/document';

export default class MyDocument extends Document {
render() {
return (
// ...
<Head>
<script
async
src="https://www.googletagmanager.com/gtag/js?id=[Tracking ID]"
/>

<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '[Tracking ID]', { page_path: window.location.pathname });
`,
}}
/>
</Head>
);
}
}
The above will track page views on page load. To track navigation add the following to _app.js:

import { useRouter } from 'next/router';
import { useEffect } from "react";

export default const App = () => {
const router = useRouter();

const handleRouteChange = (url) => {
window.gtag('config', '[Tracking ID]', {
page_path: url,
});
};

useEffect(() => {
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);

return (
// ...
);
};

 

All react js Questions

Ask your interview questions on react-js

Write Your comment or Questions if you want the answers on react-js from react-js Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---