Wassup everyone, let's see how to add google analytics to your Next.js site. Google Analytics will help you to see the performance of each page, how well the site is doing in countries, different devices, etc.
Setup Google Analytics
Go to Google Analytics and click on admin in the sidebar.
After clicking on admin you will see a screen similar to this-
Click on "Create Property", now fill in the form with your details.
You also need to give basic business details.
After you click submit your property will be created! You will see this screen and as we are using Next.js, select web-
Fill in your website URL and title-
Click on add on Add new on-page inside Tagging instructions-
Copy the ID that you see and copy it as we are going to need it!
Using Google Analytics in Next.js app
Go inside pages/_app.tsx
and these two Next.js Scripts-
<Script
strategy="lazyOnload"
src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
/>
<Script id="google-analytics" strategy="lazyOnload">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', {
page_path: window.location.pathname,
});
`}
</Script>
This is going to load google analytics via this script. As you can see we are using env variables for the google-analytics tag, so if you don't already have a .env.local
file create one and add the following-
NEXT_PUBLIC_GOOGLE_ANALYTICS=YOUR_GOOGLE_ANALYTICS_ID
Paste in the ID that we copied in the last step! Since we are changing the env variables you need to restart the server too.
As we are using the Next.js script we also need to import it-
import Script from "next/script";
Open your localhost app in one tab and google analytics in another. If you click on Real-time inside of Reports you will see that you have 1 user!
Conclusion
Adding google analytics to your Next.js app was this easy! Hope you found it useful and insightful. See ya next time ✌️
Top comments (7)
When you say:
“As you can see we are using env variables for the google-analytics tag because it must remain a secret 🤫”
Is not correct. You can use env for make the script “domain-agnostic” or whatever else, but there’s not any secret to print a prefixed NEXT_PUBLIC variable.
Oh okay, what do you mean by domain agnostic?
If you have two o more domains (like a staging portal, or another website which is based to your actual project) you can fill the .env with your actual domain; an agnostic approach to a domain which will host your software.
Regarding to .env content instead, you can expose them – and your code do it – to public. This is necessary for Google Analytics and your guests to init the correct Analytics property.
More info here: nextjs.org/docs/basic-features/env...
Oh I see, but still it would be better to use env, right?
Sure :)
Cool, also removed that secret part from blog thanks :P
Wonderful post