How to Add Google Analytics to a Next.js Application Using TypeScript

Seweryn Wawrzynowicz

Seweryn Wawrzynowicz

· 7 min read
Thumbnail

In this article, I will show you how to add Google Analytics to a Next.js application using TypeScript. Most examples I found were written in JavaScript, but this article will provide a ready-to-use TypeScript solution.

  1. Create a Google Analytics account if you don't have one already.

  2. Go to the "Admin" tab in the lower left corner. In the "Account" column, select "Create Account." Enter the account name and accept the required terms.

  3. After creating the new account, go to your Next.js application. In the main project directory, create or modify the .env.local file:

1NEXT_PUBLIC_GA_ID=your_google_analytics_tracking_id G-XXXXXXXXXX

Make sure the .env.local file is added as .env*.local in your .gitignore file. Thanks to the NEXT_PUBLIC_ prefix, Next.js automatically exposes environment variables starting with NEXT_PUBLIC_ in the client-side code (browser).

TIP: Environment variables starting with NEXT_PUBLIC_ are available on both the server-side and client-side. Therefore, it is crucial not to store sensitive information, such as passwords or secret API keys, using the NEXT_PUBLIC_ prefix.

  1. In the src directory, create a lib folder (if you don't have one already) and add a gtag.tsx file with the following code:
1declare global { 2 interface Window { 3 gtag: any; 4 } 5} 6 7export const GA_TRACKING_ID: string = process.env.NEXT_PUBLIC_GA_ID as string; 8 9// https://developers.google.com/analytics/devguides/collection/gtagjs/pages 10export const pageview = (url: string): void => { 11 window.gtag("config", GA_TRACKING_ID, { 12 page_path: url, 13 }); 14}; 15 16// https://developers.google.com/analytics/devguides/collection/gtagjs/events 17export const event = ({ 18 action, 19 category, 20 label, 21 value, 22}: { 23 action: string; 24 category: string; 25 label: string; 26 value: string | number; 27}): void => { 28 window.gtag("event", action, { 29 event_category: category, 30 event_label: label, 31 value: value, 32 }); 33}; 34

This code block declares a global Window interface with the gtag property, sets the Google Analytics tracking ID, and defines pageview and event functions for tracking page views and events, respectively.

  1. In the _app.tsx file, add the Google Analytics script:
1import type { AppProps } from 'next/app' 2import Script from 'next/script' 3import Head from "next/head"; 4import * as gtag from '../lib/gtag' 5import {useEffect} from "react"; 6import { useRouter } from 'next/router' 7 8export default function App({ Component, pageProps }: AppProps) { 9 const router = useRouter() 10 useEffect(() => { 11 const handleRouteChange = (url: string) => { 12 gtag.pageview(url) 13 } 14 router.events.on('routeChangeComplete', handleRouteChange) 15 return () => { 16 router.events.off('routeChangeComplete', handleRouteChange) 17 } 18 }, [router.events]) 19 20 return ( 21 <> 22 <Head> 23 <script 24 dangerouslySetInnerHTML={{ 25 __html: ` 26 window.dataLayer = window.dataLayer || []; 27 function gtag(){dataLayer.push(arguments);} 28 gtag('js', new Date()); 29 gtag('config', '${gtag.GA_TRACKING_ID}', { 30 page_path: window.location.pathname, 31 }); 32 `, 33 }} 34 /> 35 </Head> 36 <Script 37 strategy="afterInteractive" 38 src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`} 39 /> 40 <Component {...pageProps} /> 41</> 42)}

This code adds a script that initializes Google Analytics and listens for route changes. When a route change is detected, it calls the

1pageview
function from the
1gtag.tsx
file.

  1. If you want to track events on your website, such as form submissions, you can use the following code. Make sure you have enabled the appropriate options in Google Analytics.
1import { Component, ChangeEvent, FormEvent } from "react"; 2import Page from "../components/Page"; 3 4import * as gtag from "../lib/gtag"; 5 6interface State { 7 message: string; 8} 9 10export default class Contact extends Component<{}, State> { 11 state: State = { message: "" }; 12 13 handleInput = (e: ChangeEvent<HTMLTextAreaElement>): void => { 14 this.setState({ message: e.target.value }); 15 }; 16 17 handleSubmit = (e: FormEvent<HTMLFormElement>): void => { 18 e.preventDefault(); 19 20 gtag.event({ 21 action: "submit_form", 22 category: "Contact", 23 label: this.state.message, 24 }); 25 26 this.setState({ message: "" }); 27 }; 28 29 render() { 30 return ( 31 <Page> 32 <h1>This is the Contact page</h1> 33 <form onSubmit={this.handleSubmit}> 34 <label> 35 <span>Message:</span> 36 <textarea 37 onChange={this.handleInput} 38 value={this.state.message} 39 /> 40 </label> 41 <button type="submit">submit</button> 42 </form> 43 </Page> 44 ); 45 } 46}

This code creates a Contact component with a form. When the form is submitted, it calls the event function from the gtag.tsx file, sending the form data as an event to Google Analytics.

By following these steps, you can easily add Google Analytics to your Next.js application using TypeScript.

Copyright © 2025 . All rights reserved.
Blog created by SevDev using the template from Web3Templates