Strongly Typed Google Analytics V4 with Next.js

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


Referencing Types in a local declaration file


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


Consuming the globalized reference types

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


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 !)