Strongly Typed Google Analytics V4 with Next.js

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

terminal
tsconfig.json

Referencing Types in a local declaration file

index.d.ts

Google Analytics V4 — Acquire a Tracking ID

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

.env.local
@/lib/analytics.ts

Consuming the globalized reference types

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

`pages/_document.tsx`

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

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

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

Push — Deploy — Profit

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

--

--

--

Full-Stack Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

What’s the DOM? #5

Three.js and TypeScript (Book)

Arrays — A Unique Demonstration of Logical Thinking

Turn Any* JavaScript Library into a React Native Component

Regular Expression Matching

Manipulating the DOM Through the Console with JavaScript

Blind 75 Javascript Edition — Dynamic Programming (Part 2)

Create A Successful On-Demand Home Service App

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
Andrew Ross

Andrew Ross

Full-Stack Engineer

More from Medium

Material UI

LinkedIn Clone

So You Want to Scroll Infinitely Using React and Firebase?

Choosing the JavaScript ecosystem for a large scale enterprise app in 2022

A meme representing an excited expression (oh boy !)