Updated on: Sat Feb 06 2021
Actually all process perfectly undestandable from the example kindly provided by vercel.
But there are couple of things to mention here.
Basically all you have to do is to put your google analytics scripts in document's head modifing _document.js and add route change tracking somewhere for example in _app.js like they did in example.
First, in provided example GA_TRACKING_ID is hardcoded constant. I more tend to make it as environment variable, so in my case _document.js will look like this:
copied jsx
import Document, { Html, Head, Main, NextScript } from "next/document";
type Props = {
gaTrackingId: string;
};
class MyDocument extends Document<Props> {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
gaTrackingId: process.env.NEXT_PUBLIC_GA_TRACKING_ID,
}
}
render() {
const { gaTrackingId } = this.props;
return (
<Html>
<Head>
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${gaTrackingId}`}
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${gaTrackingId}', {
page_path: window.location.pathname,
});
`,
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
My variable called NEXT_PUBLIC_GA_TRACKING_ID and it starts with NEXT_PUBLIC_ prefix to be available on client side, because we will use its value to track route change on client side.
Next step I would create useGaPageviews react hook and place it in my _app.js file:
copied jsx
const App = () => {
useGaPageviews();
return ...;
}
// useGaPageviews/index.ts
import { useEffect } from "react";
import { useRouter } from "next/router";
import pageview from "./pageview";
const useGaPageviews = () => {
const router = useRouter();
useEffect(() => {
const handleRouteChange = (url) => {
pageview(url);
};
router.events.on("routeChangeComplete", handleRouteChange);
return () => {
router.events.off("routeChangeComplete", handleRouteChange);
};
}, [router.events]);
};
export default useGaPageviews;
// pageview/index.ts
const pageview = (url) => {
(window as any).gtag("config", process.env.NEXT_PUBLIC_GA_TRACKING_ID, {
page_path: url,
});
};
export default pageview;
Next go to https://analytics.google.com/ and create and setup account there. The process is quite intuitive. After account created we'll get id looking like G-1231231. This guy will go to our production .env file or to environment variables dashboard in vercel panel if you use vercel.