Documentation
Google Analytics

Google Analytics

This page describes how to configure your Nextra website with Google Analytics (gtag.js).

Note: This guide assumes you already have a Google Analytics measurement id (opens in a new tab) for your Nextra site.

Configuration

Create Logic for Sending Pageview and Events to Google Analytics

Create a lib/gtag.js file that exports the following:

lib/gtag.js
export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GA_ID
 
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
  })
}

Create a Custom App

Add a custom App (_app.mdx) to the pages directory of your project.

Send Pageview to Google Analytics

Import the lib/gtag.js file. And use the pageview function to send pageviews to Google Analytics whenever users navigate to a new page.

pages/_app.mdx
import { useRouter } from 'next/router'
import { useEffect } from 'react'
import * as gtag from '../lib/gtag'
 
export default function App({ Component, pageProps }) {
  const router = useRouter()
  useEffect(() => {
    const handleRouteChange = url => {
      gtag.pageview(url)
    }
    router.events.on('routeChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
    }
  }, [router.events])
 
  return (
    <>
      <Component {...pageProps} />
    </>
  )
}

Add Google Tag to your website's <head>

Use next/script (opens in a new tab) and the beforeInteractive script loading strategy (opens in a new tab) to add the inline Google Tag code to your website's <head>:

pages/_app.mdx
import { useRouter } from 'next/router'
import Script from 'next/script'
import { useEffect } from 'react'
import * as gtag from '../lib/gtag'
 
export default function App({ Component, pageProps }) {
  const router = useRouter()
  useEffect(() => {
    const handleRouteChange = url => {
      gtag.pageview(url)
    }
    router.events.on('routeChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
    }
  }, [router.events])
 
  return (
    <>
      <Script id="google-analytics-header-tag" strategy="beforeInteractive">
        {`
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', '${gtag.GA_TRACKING_ID}', {
            page_path: window.location.pathname,
          });
        `}
      </Script>
      <Component {...pageProps} />
    </>
  )
}

Add Google Analytics to Your App

Use next/script (opens in a new tab) and the afterInteractive script loading strategy (opens in a new tab) to add the external Google tag code to your website:

pages/_app.mdx
import { useRouter } from 'next/router'
import Script from 'next/script'
import { useEffect } from 'react'
import * as gtag from '../lib/gtag'
 
export default function App({ Component, pageProps }) {
  const router = useRouter()
  useEffect(() => {
    const handleRouteChange = url => {
      gtag.pageview(url)
    }
    router.events.on('routeChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
    }
  }, [router.events])
 
  return (
    <>
      <Script id="google-analytics-header-tag" strategy="beforeInteractive">
        {`
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
          gtag('config', '${gtag.GA_TRACKING_ID}', {
            page_path: window.location.pathname,
          });
        `}
      </Script>
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
      />
      <Component {...pageProps} />
    </>
  )
}

Load Measurement ID into process.env

Create a .env.local file in your project's root directory. And add your Google Analytics measurement id (opens in a new tab) to it:

.env.local
NEXT_PUBLIC_GA_ID=G-xxxxxxxxxx

Note: Replace G-xxxxxxxxxx with your measurement id.

Add Measurement ID to Your Server's Environment Variable

Add your Google Analytics tracking id to Vercel's environment variable (opens in a new tab).

Deploy Your App to Vercel

Deploy your app (opens in a new tab) to start tracking visitors and page views in your app's Google Analytics dashboard.