#nextjs
Last updated on Sep 15, 2020 by Suraj Sharma
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
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.
Related Solutions
How to build a react login form with Typescript and React hooks
4 best free website hosting sites for Javascript developers (no credit card required)
Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.