In this tutorial, you'are going to learn how you can add Google Analytics to your Next.js Website.
A typical Google Analytics JavaScript code looks like this
<script async src="https://www.googletagmanager.com/gtag/js?id=${YOUR_TRACKING_ID}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', ${YOUR_TRACKING_ID});
</script>
Adding this directly inside the Head
component on your Next project does not work because React converts it to a string before rendering,
which helps prevent cross-site-scripting attack
The best way to add the google analytics script
Open your _document.js
file, use the below code to insert the script into your _document.js
file.
import Document, { Head, Main, NextScript } from 'next/document';
export default class MyDocument extends Document {
render() {
return (
<html lang="en">
<Head>
<script async src="https://www.googletagmanager.com/gtag/js?id=${YOUR_TRACKING_ID}"></script>
<script
async
dangerouslySetInnerHTML={{
__html: `window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', ${YOUR_TRACKING_ID});`
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
Replace the ${YOUR_TRACKING_ID}
variable with your google analytics tracking ID
Now when you reload your website you can notice one 'Active Users right now' on your google analytics dashboard.
Top comments (0)