How To Properly Add Google Analytics in NextJS

React

Next.js

03/04/2023


In NextJS, Google Analytics should be loaded using the Script component which optimizes loading performance of third-party scripts. As the script should be loaded on every page of your app, it's recommend to insert it into a root file of your app, such as _app.jsx.

_app.jsx
JSX
<>
<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>
</>

The afterInteractive strategy option loads the script as early as possible after some hydration on the page has occurred. Be sure to replace GA_MEASUREMENT_ID by the measurement ID of your Google Analytics property.


WRITTEN BY

Code and stuff