Table of contents
- Getting Started
- Step 1: Add your Google Analytics ID to the .env/.env.local file in Next.js(if you don't have this file create it in the root of your folder).
- step 2: Google Analytics monitoring code should be injected into your Next.js application.
- Bonus step: Pageviews and events can be tracked using custom methods.
- Bonus step 2: Log Pageviews in your Next.js app
- Bonus step3:You might also want to Log specific events in your Next.js app
- To check that Google Analytics is connected
- Lastly: Test and Debug your page views and events with Google Analytics Debugger
*This tutorial will show you how to integrate Google Analytics into your Next.js app. The implementation is simple and does not necessitate the use of a third-party library. In approximately 5min you should be done, how sweet yeah😊? , let's get started then...
Getting Started
For this tutorial, you will be needing the following
- a Next.js project
- a Google Analytics account
- a Google ID (in case you don't have a Google Analytics account; visit Analytics, create an account, under which you would need to create a property, then finally extract your google ID)
Step 1: Add your Google Analytics ID to the .env/.env.local file in Next.js(if you don't have this file create it in the root of your folder).
Check your .gitignore file to make sure you don't accidentally commit this file..env.local should be included by default in your Next.js project, but double-check.
//inside your .env or .env.local file
NEXT_PUBLIC_GOOGLE_ANALYTICS=G-BCEKVF1M5K
step 2: Google Analytics monitoring code should be injected into your Next.js application.
extract the required google analytics code from your google analytics account/dashboard
for Next.js app
Now you insert it into the required file in between the <Head></Head>
tag ;
//For the Next.js app
//Locate your _document.js file under Pages folder and paste this script
import Document, { Html, Head, Main, NextScript } from 'next/document';
class CustomDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}
render() {
return (
<Html lang="en-US">
<Head>
//start of required script/google monitoring analytics code
{/* Global Site Tag (gtag.js) - Google Analytics */}
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
/>
<script
dangerouslySetInnerHTML={{
__html: `
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,
});
`,
}}
/>
// End of required script
</Head>
<body>
<Main />
<NextScript />
<script async src="https://www.googletagmanager.com/gtag/js?id=G-BCEXXXXM5K"></script>
</body>
</Html>
);
}
}
export default CustomDocument;
and whoola😁, we are done!, you should start seeing your metrics on your dashboard in a couple of minutes. But I have a Ramadan package for y'all tho, i bet you wanna know what it is yeah ?😊😊 So in case you also wanna log/track stuff like pageViews or Events? here's how to go about it
Bonus step: Pageviews and events can be tracked using custom methods.
Let's go on to the Google Analytics tracking section. You'll need to log page visits and, optionally, particular events triggered in your app to accurately track your users' actions. To achieve this, I recommend creating a lib folder in which you'll place all of your code related to third-party libraries, as well as a ga folder for Google Analytics. Create an index.js file in your lib/ga folder with two functions: one to track page views and the other to log events.
//inside lib/ga/index.js
// log the pageview with their URL
export const pageview = (url) => {
window.gtag('config', process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS, {
page_path: url,
})
}
// log specific events happening.
export const event = ({ action, params }) => {
window.gtag('event', action, params)
}
Bonus step 2: Log Pageviews in your Next.js app
Subscribing to your router and listening for the routeChangeComplete event is the simplest approach to log page views in your Next.js project.
To do so, open your _app.js file and utilize the useEffect function to check for new router events. There are many different types of events, but for this article, we only care about when users successfully go to a new page (routeChangeComplete).
Note: If you're interested, Next.js has a lot of other types of router events. You might be interested in logging in when an error happens, for example (routeChangeError).
mport { useEffect } from 'react'
import { useRouter } from 'next/router'
import * as ga from '../lib/ga'
function MyApp({ Component, pageProps }) {
const router = useRouter()
useEffect(() => {
const handleRouteChange = (url) => {
ga.pageview(url)
}
//When the component is mounted, subscribe to router changes
//and log those page views
router.events.on('routeChangeComplete', handleRouteChange)
// If the component is unmounted, unsubscribe
// from the event with the `off` method
return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
}, [router.events])
return <Component {...pageProps} />
}
export default MyApp
Bonus step3:You might also want to Log specific events in your Next.js app
You might be interested in logging specific events in your application now that our page views have been tracked. A list of Google Analytics Default events may be found here.
This is an example of how to keep track of user-inputted search terms:
import { useState } from 'react'
import * as ga from '../lib/ga'
export default function Home() {
const [query, setQuery] = useState("");
const search = () => {
ga.event({
action: "search",
params : {
search_term: query
}
})
}
return (
<div>
<div>
<input type="text" onChange={(event) => setQuery(event.target.value)}></input>
</div>
<div>
<button onClick={() => search()}>Search</button>
</div>
</div>
)
}
Don't forget to include your Google Analytics secret key to your environment variables once you've deployed to production.
To check that Google Analytics is connected
It takes between 24-48 hrs for data to show up in Google Analytics. However, you can check if your tag is working by looking at the Real-time view
click the explore metrics section to see what I saw, in my mind; I was like ahhh🥵 google!!, mà pà mí nau😂, so sweet, business would definitely scale with this.
Lastly: Test and Debug your page views and events with Google Analytics Debugger
If you don't see any data in Realtime, you can use the Chrome addon Google Analytics Debugger to test your Google Analytics tag. It prints Google Analytics messages to your console once it's installed and switched on, making it easy to view what's going on behind the scenes.
You now have a Next.js application that is ready to track using Google Analytics.
Come follow me🏄 🏄 🏄 on Twitter or LinkedIn if you enjoyed this essay.