Unlock the Power of Google Analytics 4 in Just 5 Minutes with Next.js and TypeScript (2023 Edition)

Aaron Janes
5 min readFeb 21, 2023

--

If you own a website, you know how important it is to track its performance and make data-driven decisions to improve its user experience and engagement. Google Analytics has been the go-to platform for website owners for over a decade, but with the new GA4, Google is taking website analytics to a whole new level. In this article, I will show you how to set up Google Analytics 4 in just five minutes using Next.js and TypeScript, so you can start taking advantage of the latest features and insights to optimize your website and grow your online business. So, fasten your seatbelt, and let’s dive into the future of website analytics with Google Analytics 4.

We won’t be installing any third-party packages to do this except for the types package from here

To Install the types

npm install --save-dev @types/gtag.js

Let’s declare a triple-slash directive for the types we added to the project. Create a index.d.ts in the root of your project and add this snippet to it

/// <reference types="gtag.js" />
declare module 'gtag.js';

An easy way to think of triple-slash-reference-types directives is as an import for declaration packages
if you want a deeper dive into this, check out the docs on this

we will now need to update our tsconfig.json file to include the following glob “ **/*.d.ts”

"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "**/*.d.ts"],

I won’t be covering how to set up the GA4 account with google, but it’s relatively straightforward if you follow this guide

It only takes about 5 mins to set up today, and we will only focus on the code implementation. Just make sure to note down your GA-ID. It looks like this ‘G-XXXXXXXX

Now that you have a GA-ID lets add it to your projects .env file

like so:

NEXT_PUBLIC_GA_ID="G-<YOUR ID>"

Let’s set up a lib folder to hold our helper functions. Create a lib folder in the root of your project and create a gtag.ts file in the folder. Add the following snippet to the file.

export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GA_ID

/**
* This function is used to track page views.
* https://developers.google.com/analytics/devguides/collection/gtagjs/pages
* */
export const pageView = (url: URL) => {
console.log('pageView', url)
window.gtag('config', GA_TRACKING_ID, {
page_path: url
})

}

/**
* https://developers.google.com/analytics/devguides/collection/gtagjs/events
* If you want to track events, you can use the gtag.js event method.
* */
export const event = (action: Gtag.EventNames, { event_category, event_label, value }: Gtag.EventParams) => {
window.gtag('event', action, {
event_category,
event_label,
value
})
}

Now lets update the _app.tsx file with the following code. If you are not familiar with how to set up a _app.tsx file check out the Next.js documentation here

// add these imports 
import { useRouter } from 'next/router'
import { useEffect } from 'react'
import * as gtag from '../lib/gtag'

export default function App({ Component, pageProps }: AppProps) {

// add this snippit
const router = useRouter()
useEffect(() => {
const handleRouteChange = (url) => {
gtag.pageView(url)
}
router.events.on('routeChangeComplete', handleRouteChange)
return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
}, [router.events])
// end of snippit

return (
..... your code

)}

Next will update the _document.tsx to load the GA4 script. If your not familiar with setting up a customer _document.tsx here is the documentation

import { Head, Html, Main, NextScript } from 'next/document'
import Script from 'next/script'
import { GA_TRACKING_ID } from '../lib/ga/gtag'

export default function Document() {
return (
<Html lang='en'>
<Head>
<>
<Script
id={GA_TRACKING_ID}
strategy='afterInteractive'
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
/>

<Script
id={GA_TRACKING_ID}
strategy='afterInteractive'
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`
}}
/>
</>
</Head>
<body className='bg-white text-black'>
<Main />
<NextScript />
</body>
</Html>
)
}

You can now track all your page views if everything is configured correctly. This data gets pushed via the window.data layer we have configured above. For a deeper dive, check out the documentation here

The data will take about 24–48 hours to populate the GA4 dashboard. Since we don’t want to wait for 24hrs to see if we have done things correctly, here is a bit of a hack Open your browser console up and type

console.log(datalayer)

You will be able to see the data you are pushing to the data layer

You probably only want to push data when you are in production, so let us modify the _document.tsx file to look like this

import { Head, Html, Main, NextScript } from 'next/document'
import Script from 'next/script'
import { GA_TRACKING_ID } from '../lib/ga/gtag'

export default function Document() {
return (
<Html lang='en'>
<Head>
{/*Conditionally render script only if in production */}
{process.env.NODE_ENV === 'production' && (
<>
<Script
id={GA_TRACKING_ID}
strategy='afterInteractive'
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
/>

<Script
id={GA_TRACKING_ID}
strategy='afterInteractive'
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`
}}
/>
</>
)}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}

In conclusion, setting up Google Analytics 4 with Next.js and TypeScript is essential for any website owner who wants to make data-driven decisions and optimize their online presence. With the straightforward approach outlined in this article, you can quickly set up the new GA4 and start tracking your website’s performance in real time. So, what are you waiting for? Take five minutes to set up Google Analytics 4, and unlock valuable insights into your website’s traffic, user behaviour, and more.

Thanks for reading my article on unlocking the power of Google Analytics 4 in just 5 minutes using Next.js and TypeScript! I hope you found it informative and useful. If you’re interested in learning more about website analytics, web development, and other tech-related topics, be sure to check out my blog.

www.stackfails.io

Good luck, and happy tracking!

--

--