Add Google Analytics to a Next.js application
To add scripts to nextjs application, you need to use the Script
tag as follows:
import Script from 'next/script'
export default function App({ Component, pageProps }) {
return (
<>
<Script id="my-script">{`console.log('Hello world!');`}</Script>
<Component {...pageProps} />
</>
)
}
Note: id is a must while using Script
tag (for pre-rendered applications)
Simlarly you need to setup google analytics scripts in the application. Here is a code sample for the same:
import Script from 'next/script'
export default function GoogleAnalytics() {
return (
<>
<Script
id="google-analytics-load"
strategy="lazyOnload"
src={`https://www.googletagmanager.com/gtag/js?id=G-HSLQYKMYGM`}
/>
<Script strategy="lazyOnload" id="google-analytics-init">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-HSLQYKMYGM', {
page_path: window.location.pathname,
});
`}
</Script>
</>
)
}
Then you can add the same to the app layout wrapper:
import GoogleAnalytics from './google-analytics'
export default function App({ Component, pageProps }) {
return (
<>
<Head>
<title>jsbisht.in</title>
<meta name="description" content="jsbisht.in" />
<link rel="icon" href="/favicon.ico" />
</Head>
<GoogleAnalytics />
<Component {...pageProps} />
</>
)
}