Add Google Analytics To Next.js Website

Add Google Analytics To Next.js Website

2 min read · 272 words · Shared April 29, 2021 by

Article Summary: Connect Google analytics to your Next.js website and track clicks, scrolls, page views, and more.

Introduction

Adding Google analytics to a Next.js website seems complicated, but is not that difficult. To begin, make sure you have a Google Analytics account with your project set up.

Add The Tracking Code

Create a folder in your Next.js root directory called lib. Inside of here, create a file named gtag.js. Paste in the following code:

gtag.js
export const GA_TRACKING_ID = 'G-XXXXXXXXXX'

// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = (url) => {
    window.gtag('config', GA_TRACKING_ID, {
        page_path: url,
    })
}

// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }) => {
    window.gtag('event', action, {
        event_category: category,
        event_label: label,
        value: value,
    })
}

Replace the 'G-XXXXXXXXXX' with your tracking id (This can be found in the Google Analytics admin pannel for your website).

Add GTAG To Document.js

Next, open up _document.js. If you do not have this file created already, follow along with the docs and and create a custom _document file for your site. Inside of here we will import our gtag and use it.

_document.js
import { GA_TRACKING_ID } from '../lib/gtag'
// other imports

export default class MyDocument extends NextDocument {
    render() {
        return (
            <Html lang="en">

                {/* other code */}

            <Head>
                    {/* Global Site Tag (gtag.js) - Google Analytics */}
                    <script
                        async
                        src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
                    />
                    <script
                        dangerouslySetInnerHTML={{
                            __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${GA_TRACKING_ID}', {
              page_path: window.location.pathname,
            });
          `,
                        }}
                    />
            </Head>

            {/* Other code */}

        </Html>
        )
    }
}

That's it! Once you deploy to Vercel (or another hosting service of your choice) you should see analytics coming through after 5 minutes or so.

Realtime Views
View Full Image

·

Realtime Views

Edit on GitHub

Related Tags

    #nextjs

Related Posts

Add Algolia's InstantSearch to Next.js - A Quickstart · December 17, 2021
Generate A Dynamic Sitemap In Next.js Website · September 27, 2021
Add Splitbee Analytics To Next.js · July 20, 2021
Connect Firebase To Next.js · April 15, 2021

On This Page

Introduction

Add The Tracking Code

Add GTAG To Document.js

View Related Posts

December 17, 2021

algolia.png

Add Algolia's InstantSearch to Next.js - A Quickstart

September 27, 2021

nextjs-light.png

Generate A Dynamic Sitemap In Next.js Website

July 20, 2021

splitbee.png

Add Splitbee Analytics To Next.js

April 15, 2021

firebase.png

Connect Firebase To Next.js


Loading author data...

    Legal

    Terms

    Disclaimer

    Privacy Policy


    Carlson Technologies Logo© Copyright 2021 - 2024, Carlson Technologies LLC. All Rights Reserved.