4 min read

Implement Google Analytics in Next.js

Configure a GA4 Property in your app.

ByAmir Ardalan
Share on X

Setting up Google Anaylytics is fairly straight forward, but it can be easy to get tripped up when doing so in Next.js for the first time. In this guide, I will show you how to get GA running in your Next.js app in just a few easy steps.

Make sure to create a GA4 property in Google Analytics. Universal Analytics will no longer be supported as of July 1, 2023.

Add your Google Analytics ID to .env

If you don't already have one, create a file called .env. Make sure to add this file to your .gitignore as this is a place to store sensitive information that should never be uploaded to a git repository.


Add Data Layer to _document.tsx

If you don't already have one, create a custom Document page and add the script tags provided by Google Analytics:

1// _document.tsx 2 3import { Html, Head, Main, NextScript } from 'next/document' 4 5export default function Document() { 6 return ( 7 <Html> 8 <Head> 9 <script 10 async 11 src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_ANALYTICS_ID}`} 12 /> 13 <script 14 dangerouslySetInnerHTML={{__html: ` 15 window.dataLayer = window.dataLayer || []; 16 function gtag(){dataLayer.push(arguments);} 17 gtag('js', new Date()); 18 gtag('config', '${process.env.NEXT_PUBLIC_ANALYTICS_ID}'); 19 `, 20 }} 21 /> 22 <Head /> 23 <body> 24 <Main /> 25 <NextScript /> 26 </body> 27 </Html> 28 ) 29} 30 31

Create gtag.ts in lib Folder

This will get the initial tracking set up for your app.

1// gtag.ts 2 3declare global { 4 interface Window { 5 gtag: any 6 } 7} 8 9export const pageview = (url: URL) => { 10 window.gtag('config', 11 process.env.NEXT_PUBLIC_ANALYTICS_ID, { 12 cookie_flags: 'SameSite=None;Secure', 13 page_path: url, 14 }) 15} 16 17export const event = ({ action, category, label, value }) => { 18 window.gtag('event', action, { 19 event_category: category, 20 event_label: label, 21 value: value, 22 }) 23} 24

Create useGtag.ts in utils Folder

Here we will utilize Next's useRouter in order to send route information to Google Analytics.

Technically, this isn't a custom hook since it doesn't have state, but you can't utilize useEffect inside of a normal function (and this isn't a component). I have chosen this name and path for code organization purposes, but you can alternatively put the useEffect directly in _app.tsx
1// useGtag.ts 2 3import { useEffect } from 'react' 4import { useRouter } from 'next/router' 5import * as gtag from '@/lib/gtag' 6 7const useGtag = () => { 8 const router = useRouter() 9 useEffect(() => { 10 const handleRouteChange = (url: URL) => { 11 gtag.pageview(url) 12 } 13 router.events.on('routeChangeComplete', handleRouteChange) 14 return () => { 15 router.events.off('routeChangeComplete', handleRouteChange) 16 } 17 }, [router.events]) 18} 19 20export default useGtag 21

Invoke useGtag Function in _app.tsx

1//_app.tsx 2 3import useGtag from '@/components/useGtag' 4 5function MyApp({ Component, pageProps }) { 6 Analytics() 7 return <Component {...pageProps} /> 8} 9 10export default MyApp 11

Add Environment Variable to Production Server

This is an easy step to forget. Be sure to set up NEXT_PUBLIC_ANALYTICS_ID (from your .env file) on your server.

Filter Internal Traffic

Now that GA is up and running, the final step is to ensure you aren't tracking your own visits. You will need your IP address. Once you have your IP, log in to Google Analytics.

  1. From the main page, look to the bottom left of the screen and click on the gear (Admin) icon ⚙️.
  2. On the Admin screen, ensure you are on the correct GA4 property that you just set up. Click on Data Streams.
  3. Click the Add stream button and click on your app address.
  4. On the "Web stream details" panel, at the very bottom, click More Tagging Settings.
  5. On the "More tagging settings" panel, click Define internal traffic
  6. Click on the Create button, add a Rule name (e.g. Home), and leave traffic_type value as "internal". Finally, select Match type: IP Address Equals and then paste your IP address into the Value input.
  7. Click the Add condition button. Repeat these steps for any other IPs you want to filter.
  8. Click the Admin gear icon ⚙️, then select Data Settings > Data Filters
  9. On the "Data filters" page click the three dots to the right of the Internal Traffic filter and select "Activate Filter".

Final Thoughts

That's it! 🎉 If you run into any issues, I recommend installing Google Analytics Debugger, it's available for Firefox and Chrome.

Google Analytics is a great way to keep track of who visits your site, where they are coming from, what they are looking at, and how long they are spending doing so. While it's packed with features and customizations, the UI is a bit clunky and it can be overkill for a small site. I have been on the lookout for something modern, lightweight, and free. If you know of anything that fits that description, hit me up on Twitter and let me know!

Did you enjoy this post?

© 2024 Amir Ardalan0 views