Analytics basics for a NextJS site

Hannah Reed
Hannah Reed
Web analytics illustration

Web analytics are key to collecting insights and understanding your users' intent, behaviour, pain points, needs and more. Installing multiple tracking pixels can seem cumbersome and can slow down your site's speed performance. However, there is a wide range of options to set these up efficiently. This guide will walkthrough how to setup basic tracking via Google Tag Manager. The platforms mentioned in this guide offer free accounts.

Overview of analytics tracking platforms

Starting with the well-known Google Marketing Platform there is

  • Google Search Console that provides user search data.
  • Google Analytics that provides site user analytic data.
  • Google Ads that provides user search and ads analytics data.
  • Google Tag Manager that provides efficient pixel (tag) tracking management.

From the next largest search engine, Bing/Microsoft Advertising, there is

  • Bing Website Master which provides user search data.
  • Microsoft Ads which provides user search and ads analytics data.

Other top social media platforms to mention are

  • Facebook ads campaign data.
  • LinkedIn ads campaign data.
  • Twitter (X) ads campaign data.

The majority of these mentioned, I would recommend any business to have profiles on as a basis for building a strong online brand presence.

Setting up Third-Parties libraries for NextJS

It's important to mention that when using any tracking pixels to collect data on users moving between their site or search engine and your site, it's best practice to make your site users aware and give them the option to accept the tracking 'cookies' or not. A cookie banner along with a privacy policy page is a good way to implement this and comply with legal regulations such as 'GDPR' in EU countries.

1. Install the Next Third Parties libraries

Open your project's directory from your Terminal (use GitHub desktop shortcut 'Open the repository in Visual Studio Code', then the keyboard shortcut ctr + opt + ` to open a Terminal window) and run the command:

sudo npm i @next/third-parties

This should globally install the necessary template code for installing Google Tag Manager on your site.

2. Import the Google Tag Manager library component in your project layout

If you haven't already created a Google Tag Manager (GTM) account do so now. And create a new GTM container for your site. This will have a unique data layer ID you can find in the Admin settings or at the top of the page, which looks like 'GTM-ABCD1234'.

Insert the following code in your .../app/layout.tsx file 'head' section, before any 'body' elements:

<GoogleTagManagergtmId="GTM-ABCD1234" />

replacing the "GTM-ABCD1234" with your GTM container's ID;

and import the GTM library at the very top of the file:

import { GoogleTagManager } from '@next/third-parties/google'

Your layout.tsx file may then look like:

import 'tailwindcss/tailwind.css'

import { GoogleTagManager } from '@next/third-parties/google'
import { DM_Sans } from 'next/font/google'
const sans = DM_Sans({
variable: '--font-sans',
subsets: ['latin'],
weight: ['100', '400', '1000'],
})

export default async function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html
lang="en"
className={`${sans.className}`}
>
<GoogleTagManager gtmId="GTM-ABCD1234" />
<body>{children}</body>
</html>
)
}

3. Load the GTM component in each page layout

Similarly, apply the same code to each page layout 'header' section in your project for example, in the file '...pages/BlogPage.tsx':

import { GoogleTagManager } from '@next/third-parties/google'

...

return (
<>
<BlogPageHead .../> ...

<GoogleTagManagergtmId="GTM-ABCD1234" />

And that's it. Next up would be to test that it works. The next section will walkthrough setting up your GTM container to implement Google Analytics tracking, testing and more.

Installing Google Analytics via Google Tag Manager

First up, create a Google Analytics account and property for your site. Your new 'web data stream' will come with a 'Measurement ID'. This is what you'll use to install Google Analytics data collection on your site.

Tip: This is also a good time to setup your Google Search Console account and verify your site. Then link it to your Google Analytics account by going into Settings > Product Links > Search Console Links. It will automatically import and enable you to blend the data in the future when there are large enough data samples.

Go back to your GTM container and prep it...

1. Prep your GTM by enabling Variables

From the left-hand side navigation, go into Variables > Configure.

Tick all of the 'built-in variables' you think you'll use in the future. At minimum tick all of the Pages variables (Page URL, Page Hostname, Page Path, Referrer etc.) and I would recommend Event, Container ID, HTML ID, and all of the Clicks, Scrolling, Visibility variables.

Tip: the 'Forms' built-in variables are not the most reliable at picking up changes in all types of forms. You'll probably find that creating a custom CSS or HTML class or div name in the backend code of your form's submit confirmation message and custom Element Visibility trigger for this in GTM along with advanced 'Observe DOM changes' settings to be far more accurate.

2. Create essential Triggers

An essential 'trigger' to create in your GTM container is one that 'fires' whenever a page loads for a user on your site. There are multiple different ones to choose from. For now, I would only concern yourself with either the New > Trigger Configuration > Page View > 'Page View' built-in trigger type or the Page View > 'Consent Initialization' beta trigger type if your site has a cookie banner implemented.

Tip: If you leave the trigger name field blank and hit the 'save' button after selecting a built-in trigger it will autofill in the name of the trigger for you.

Create the 'Consent Initialization' trigger just as well if you want to create a cookie banner from a Google Consent Manager Partner template tag.

Tip: Create the 'History Change' built-in trigger type for dynamic, client-side rendering sites. This will enable firing on "virtual or single page webapps" without having to reload the entire page in order to track events.

3. Create your Google Tag

In the Tags workspace click New > Tag Configuration > Google Tag.

Go back to your Google Analytics account data stream "MEASUREMENT ID" to copy. It looks something like "G-XXXXXXXXXX".

Go back to your GTM Google Tag configuration and paste it into the Tag ID field.

Then click to edit the Triggering and select the 'All Pages' Page View trigger type, or if you're using a cookie banner select the 'Consent Initialization - All Pages' Consent Initialization trigger type.

Tip: The "Consent Initialization" trigger types only works for Google recognized Consent Manager Partners (CMPs). Check out the list of providers to simplify a dynamic cookie banner on your site. You'll find that many provide free "no-code" cookie banners using GTM i.e. consentmanager.net and Cookiebot.

4. Test, Publish and Test again

In GTM, you can always test and debug your tags in the 'Preview' mode. Locate it towards the top of your GTM dash. You'll be prompted to connect to your domain and then the Tag Assistant and Debugging tabs should automatically launch in your browser. Click around in the Debugging tab as you intend to track your users and then check in the Tag Assistant tab that the appropriate triggers have fired.

After previewing and checking your GTM setup, hit the Submit button. Enter a version title and descriptions of what new tags are installed for self-reference and then hit Publish.

Now, test your Google Analytics installation from your Google Analytics property Reports > Real-time.

Close out of all window pages of your site. In your browser settings clear any caching of your site (shortcut cmd + shift + R on Google Chrome for Mac). Then open up only one tab of your homepage.

Back in your Google Analytics Real-time reporting you should see 1 unique user and page view appear.

Troubleshooting tip 1: after installing GTM it may take a while to propagate on your live site. Check that it's deployed to your live site. Then from your domain register manager (e.g. Cloudflare domain Caching Configuration settings) Purge all caching.

tip 2: if the Real-time report cards don't show any hits after waiting a few minutes then Google may have already automatically filtered out your IP address as 'Internal Traffic'. So you can try the test by disconnecting from your wifi and using your mobile network or a VPN.

Setting up Google Ads tracking

Google Ads has some brilliant tools that many professionals use regardless of whether they are managing active PPC campaigns. You can setup a free account by creating a draft campaign and adding billing info. Remember to switch the campaign to 'pause' and change the UI 'Appearance' settings to 'expert mode'.

1. Integrate Google Ads and Google Analytics

This step is for if you're using Google Analytics. Assuming you've completed the steps in the previous section for installing your Google Analytics via GTM, go into your Google Analytics account admin settings. Locate 'Product links' > Google Ads links > Link > Choose Google Ads accounts

then tick your Google Ads Account there and follow the steps to confirm the integration. This way you won't need to create a separate Google Tag in GTM for your Google Ads. The Google Tag you've already created for Google Analytics will automatically share data (and import data from) with Google Ads.

Or create a tag for Google Ads tracking

In the case that you don't want to use Google Analytics, you'll need to locate your Google Ads Google Tag ID. Make sure your Google Ads workspace appearance is in the 'new design' advanced mode. Then from the side panel of settings go to Tools > Data Manager > Google Tag > Manage > Admin > Install this Google Tag > Install Manually

From the code, pick out the line that states your unique ID which will look something like "AW-1234567890". You may also see it at the top of the window. Copy it to your clipboard.

Now go to your GTM account to find the built-in tag in Tags > New > Tag Configuration > Google Ads > Google Tag.

And paste your Google Ads tracking ID in the "Tag ID" field.

Next set the Triggering to "Consent Initialization - All Pages", then finally, save it.

2. Create a Conversion Linker

You need this for tracking "converted" customers or "leads". This is essential in the world of digital marketing and having a rich data analytics strategy in place. The Google Ads data source is the best in providing insight as to your target audience personas and interests. By blending it with your Google Analytics site behaviour analytics you can uncover actionable insights to continually improve your marketing and content.

Back in your GTM account, select the built-in tag in Tags > New > Tag Configuration > Google Ads > Conversion Linker.

Next set the Triggering to "Consent Initialization - All Pages", then finally, save it.

3. Create a Remarketing Audience and Tag

"Remarketing campaigns" are necessary for increasing your brand awareness and online "impressions". If you've linked your Google Analytics and Google Ads then Google will have already provided a default audience segment in your Google Ads account for "all users" that have visited your site within the time period set (default is usually a 'last 30-day' window although you can adjust this in your settings).

Go to your Google Ads Tools settings > Shared Library > Audience Manager > Your data sources > Google Ads Tag > [click the 3 dots in the top-right corner] > Edit source > Save and continue > Tag Setup > Use Google Tag Manager.

This should display your "Conversion ID". Copy it to your clipboard and go to your GTM account now.

In your GTM account, select the built-in tag in Tags > New > Tag Configuration > Google Ads > Google Ads Remarketing.

Paste your Conversion ID in the relevant field. Next, set the Triggering to "Consent Initialization - All Pages", then finally, save it.

4. Create a custom conversion tag

Google automatically creates some typical conversion events for you (in both Google Analytics and Ads) such as website visits, page scrolling, and file downloads.

With more complex sites, you'll want to track more specific order of events as 'conversions'. And sometimes, the Google preset conversions don't get it right.

This is where GTM comes in handy as a 'no code' way to create and customise as much event tracking you need without having to ask a developer to work the backend code of the site.

In your GTM account start by creating a custom trigger. This could be a trigger to fire when a user clicks a certain button on a page or when they scroll 75% of the way to the bottom of a blog article, for example. Have a look through the built-in triggers provided by Google and pick one that's relevant for you. For the most part, the default settings will suffice but if you're unsure then contact me.

The important part is to switch "This trigger fires on" from "All Pages" to "Some Pages". In the drop-down, select "Page Path", "Contains" and then in the free form value field fill in the part of the landing page URL you want the event to be counted on e.g. "/blogs/".

Tip: You can use more than one custom trigger in a tag and even use a custom trigger as an exemption rule.

Once you have your custom trigger(s) saved. Go into the Tags and create a new Tag > Tag Configuration > Google Ads > Google Ads Conversion Tracking.

In the first field, your Conversion ID will be the same one found in your Google Ads account g-tag. Go to Tools > Data Manager > Google Tag > Manage > Admin > Install this Google Tag > Install Manually.

From the code, pick out the line that states your unique ID which will look something like "AW-1234567890". You may also see it at the top of the window. Copy it to your clipboard and back in GTM, paste it in the relevant field.

For the next field, "Conversion Label" enter a detailed primary name of the event you're tracking. This will show up like a category label.

In the "Conversion Value" field enter a detailed name of what the event is that you're tracking.

Next, in the Triggering configuration, select your custom Trigger(s).

Finally, give your new Tag a detailed name and save.

Last notes

By now you will have hopefully familiarised yourself with GTM and gotten the hang of the built-in features that make it all a little easier. It should be fairly straightforward to make the tags for other campaign platforms, in that you would follow similar steps to what's been detailed. Also, social media platforms usually recognise GTM as a popular method for installing the tracking pixels and provide template Tags you can click to connect and auto-create for you from the account settings.

You'll be able to see the data from the individual platforms themselves and Google Analytics Reports (Traffic acquisition reporting).

You'll also be able to further blend the data in the Google Analytics Explore (Exploration) tool and Google Looker Studio. All in all, there's a wealth of benefit in understanding your audience and how you can improve the experience and provide more relevant and helpful content.