Sometimes, we want to use Google Analytics with a React Next.js app.
In this article, we’ll look at how to use Google Analytics with a React Next.js app.
How to use Google Analytics with a React Next.js app?
To use Google Analytics with a React Next.js app, we can use the Script
component.
For instance, we write
import Script from "next/script";
import Head from "next/head";
export default function Index() {
return (
<>
<Head>
<title>Next.js</title>
</Head>
<Script
src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){window.dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_MEASUREMENT_ID');
`}
</Script>
</>
);
}
to add the Script
component which has the Google Analytics code.
The Script
component as a script tag in the head element.
Conclusion
To use Google Analytics with a React Next.js app, we can use the Script
component.