Analytics
Sometimes we use Google analytics to record user interactions with the activation. This is useful for understanding how users interact with the site and what features are most used.
Setting up Google Analytics
DO NOT USE THE NEXT.JS GTM
We need to add the gtag global methods in order to control how the analytics are sent. The next.js GTM plugin does not allow us to do this.
Firstly add your snippet to the root layout.tsx
. Your snippet should look something like this:
import Script from "next/script";
const GA_ID = process.env.NEXT_PUBLIC_GA_ID;
...
{GA_ID ? (
<>
<Script
src={`https://www.googletagmanager.com/gtag/js?id=${GA_ID}`}
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_ID}');
`}
</Script>
</>
) : null}
...
With this snippet, we can now use the gtag
function to send events to Google Analytics.
TIP
It is highly recommended to have 2 GA accounts, one for development and one for production. This way you can test your analytics without affecting the production data.
Custom Events or how to control the session
Normally, we want to control when a session starts. Since activations use the same browsers for all users.
We can use the following snippet to reset the session and send a page view event. You do not need to send a page view on every page (ga and next will do that automatically), but if you have other buttons that trigger actions but not page changes you can add them manually.
// src/lib/ga.ts
declare global {
interface Window {
gtag: (...any: any[]) => void;
}
}
export const resetSession = () => {
if (window.gtag) {
const newSession = `session_${Math.floor(Math.random() * 1000)}`;
localStorage.setItem("ga_session", newSession);
window.gtag("set", { user_properties: { session_id: newSession } });
window.gtag("event", { session_start: { session_id: newSession } });
}
};
export const pageView = (title: string, path: string) => {
if (window.gtag) {
window.gtag("event", "page_view", {
page_title: title,
page_location: window.location.href + path,
});
}
};
Analytics Best Practices.
Add page titles to your pages
The easiest way to track page views is to make sure each page has a unique title, this is how GA stores views by default.
//layout.tsx | page.tsx
import type { Metadata } from "next";
export const metadata: Metadata = {
title: "Your Current Page title",
description: "Description are less important for GA",
};