Google Analytics is a great tool to collect and analyze data from websites and mobile apps to help companies and teams grow. It's free and easy to use and has many excellent features like real-time overviews and reports. Today we will learn how to integrate it with Next.js one of the best web frameworks recently to get the best benefit of both.
First of all, you should have a Gmail Account, if you don't have on create one before jumping to the next step.
Go to Google Analytics Dashboard.
If this is the first time to log into Google Analytics Dashboard, you will see this screen, click on “start measuring” and create account and property
If you already have an account, go to “Admin” on the sidebar.
After creating the account and property, you should see this screen.
All that we need from this screen is the measurement id.
In your project folder, find the file pages/_app.js
and we need to import the <Script />
component.
import Script from "next/script";
and then add the following code to the JSX:
<Script
src="https://www.googletagmanager.com/gtag/js?id=YOUR_MEASUREMENT_ID"
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{
`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'YOUR_MEASUREMENT_ID');
`;
}
</Script>
That's it, congratulations! You can now start measuring your website with Google Analytics 🎉