If you have started working with Next.js recently and wanted to add Google Analytics to your website, then you are at the right place!
Creating a Google Analytics tag
Login to https://analytics.google.com/analytics/web/ with your Google account.
Now click on the Settings Icon (βοΈ Admin) at the bottom and click on Create Account
(If you already have an account, you can click on Create Property).
Now fill in the account name:
Fill in the property details along with the time zone and currency:
Finally, fill in the business details and click on Create:
Now you will be redirected to a page with the following options. Here click on Web.
In the next step provide your website details and click on Create stream.
Now you will be provided with a measurement id. Make a note of it. It will be used in the next step.
Creating a Next.js app
Now create a Next.js app, if you do not have one, using the following command:
npx create-next-app@latest next-ga-integration
Adding Google Analytics
Create a file named gtag.js
with the following content (replace GA_TRACKING_ID
value with yours):
export const GA_TRACKING_ID = "G-226MBLFR8V" //replace it with your measurement id
// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = url => {
window.gtag("config", GA_TRACKING_ID, {
page_path: url,
})
}
// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }) => {
window.gtag("event", action, {
event_category: category,
event_label: label,
value: value,
})
}
We have 2 functions here:
- pageview: To track users navigating to different pages.
- event: To track events like add to cart, place order, etc.
Now open _app.js
and include the following code:
import "@/styles/globals.css"
import Script from "next/script"
import { useRouter } from "next/router"
import { useEffect } from "react"
import * as gtag from "gtag"
export default function App({ Component, pageProps }) {
const router = useRouter()
useEffect(() => {
const handleRouteChange = url => {
gtag.pageview(url)
}
router.events.on("routeChangeComplete", handleRouteChange)
return () => {
router.events.off("routeChangeComplete", handleRouteChange)
}
}, [router.events])
return (
<>
<Script
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
/>
<Script
id="gtag-init"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${gtag.GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
<Component {...pageProps} />;
</>
)
}
In the above code:
- We have included the Google Analytics script and loading it after the page becomes interactive so that it doesn't affect the page loading time.
- We have a
useEffect
where we listen to route changes and call thepageview
function, defined insidegtag.js
. This is required since in Next.js, whenever routing happens, the page doesn't completely reload and Google Analytics will not be able to pick up the route change automatically.
Now your application is setup with Google Analytics and you can track the live users:
Top comments (4)
I think this way is safer:
Indeed...wouldn't it be more useful if you used GTM and then add Analytics there?
How do we do it in app route
Put the code in Global Layout.tsx