April 29, 2021

2 min read


Add Google Analytics To Next.js Website

Easily connect your website to Google Analytics.

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. 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:


export const pageview = (url) => {
    window.gtag('config', GA_TRACKING_ID, {
        page_path: url,

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

Halfway There!

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.

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

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

                {/* other code */}

                    {/* Global Site Tag (gtag.js) - Google Analytics */}
                            __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${GA_TRACKING_ID}', {
              page_path: window.location.pathname,

            {/* Other code */}


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

Written By Benjamin Carlson

Founder Coffeeclass

More Articles By Benjamin Carlson

Sections 📑

Halfway There!