Let's get right in.
Table of Contents
- Getting the Google Analytics Tracking Code
- Create a custom document file
- Tweaking Google Analytics Code to fit NextJs structure
- Deploy
Step 1 - Getting the Google Analytics Tracking Code
Go to the Google analytics website & get your tracking code.
Keep that code snippet at some place while we set up the rest of the application.
Step 2 - Create custom document file
Now the reason why we don't put the code snippet anywhere else... This is because we want the script to be loaded on every single page.
And the best way to ensure that is by putting your code in a global document file.
Go to your pages
folder and create a _document.js
file if you don't have it already.
Paste this into your _document.js
file:
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
render() {
return (
<Html lang='en'>
<Head>
...
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
Step 3 - Tweaking Google Analytics Code to fit NextJs structure
We cannot simply paste the copied Google analytics code into NextJs. It will not work like that.
If you are looking for a plug-and-play solution. Try out Veonr Analytics. It's completely free.
Anyway - we want to convert our code snippet to look something like this:
<script
async
src="https://www.googletagmanager.com/gtag/js?id=YOUR_ID_HERE"
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'YOUR_ID_HERE', {
page_path: window.location.pathname,
});
`,
}}
/>
Instead of copying the above code block. You can rewrite the existing Google Analytics code in your editor itself.
If you do copy & paste the above code block though. Make sure to replace YOUR_ID_HERE
with your actual analytics ID.
Step 4 - Deploy
That's it. Your code is ready to be taken live. Make sure to deploy your app to the server & try to visit the website to see if it started tracking properly.
Conclusion
Setting up Google Analytics in your NextJs app shouldn't be that difficult.
This is why we recommend using a highly accurate & performant solution instead. Like Veonr Analytics.
Thanks for reading this piece. Hope that analytics is now working for you. If in case you are still unable to figure out why it's not working.
Consider trying alternative options to see if the problem is with your code or with the script.
Cheers!
Spread the love. Like butter. Share this article with your friends.