Strongly Typed Google Analytics V4 with Next.js

Install `@types/gtag.js` as a dev dependency

Open your terminal and run

terminal
tsconfig.json

Referencing Types in a local declaration file

First, create a root `index.d.ts` file. This is where we will configure a triple-slash directive types-reference to the `@types/gtag.js` dev-dependency. Once configured and declared, the types contained within `@types/gtag.js` will be globally available for consumption — no imports required. Sure is nice

index.d.ts

Google Analytics V4 — Acquire a Tracking ID

Head over to google analytics and sign in. If you don’t have an account, create one, then sign in. Once signed in and on the landing page, click on the `Admin` gear icon in the bottom left corner then select `+ create property` as pictured below

Create Property
Property Setup
analytics options

Configure a Data Stream for your Property

Configure a datastream
data stream setup
Web stream details

Back to your Code Editor

After copying the measurement ID for your new property, open your code editor, create a `.env.local` file in the root directory, then add the following key-value pair

.env.local
@/lib/analytics.ts

Consuming the globalized reference types

As mentioned previously, there is no need to import anything to consume the reference `@types/gtag.js` types declared in the root `index.d.ts` file. Let’s start with `pageview`:

@/lib/analytics.ts
Intellisense on hovering window.gtag
@/lib/analytics.ts
EventNames type
EventParams interface
@/lib/analytics.ts final

`pages/_document.tsx`

Nearly finished. Navigate to `pages/_document.tsx` and import the `GA_TRACKING_ID` constant that we exported from `@/lib/analytics.ts`

imports in @/pages/_document.tsx
@/pages/_document.tsx returned TSX
@/pages/_document.tsx full

Wrapping this up in the root `pages/_app.tsx` file

Navigate to the custom `pages/_app.tsx` file and import `gtag` as a wildcard (*) from `@/lib/analytics`. We will also be needing `useEffect` from `React` and `useRouter` from `next/router`. Add the following code within the default export function but before the returned tsx in your `_app.tsx` file:

@/pages/_app.tsx handle route change
@/pages/_app.tsx full

Push — Deploy — Profit

Ensure that your deployment environment is provided with the `NEXT_PUBLIC_GA_TRACKING_ID` key-value pair, push your changes, successfully deploy, profit.

add the NEXT_PUBLIC_GA_TRACKING_ID key-value pair to your production environment
Data trickles in…

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store