How to add Google Analytics to your Next.js project

Cover Image for How to add Google Analytics to your Next.js project
Marouane Reda
Marouane Reda
If you need to understand the basics of Next.js, i recommend this course. (Disclaimer : this is an affiliate link that may earn me a small commission, but with no extra cost to you if you choose to enroll)

Add your Google Analytics ID to your Next.js .env.local file

After getting your Google Analytics ID from your Google Analytics account, add it to your .env.local file ( create the file in the root directory if it doesn't exist) :


Create functions to track pageviews and events

Create a file ( here named gtag.js under /lib) containing the custom functions to track pageviews and events on your site :

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,

Add your Google Analytics ID to your app

In the _document.js file, we will add the tracking script wit our gtag ID (create _document.js in your root project if it doesn't exist):

import Document, { Html, Head, Main, NextScript } from 'next/document'

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

export default class MyDocument extends Document {
  render() {
    return (
          {/* 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,
          <Main />
          <NextScript />

Log pageviews in your Next.js app

Now modify your _app.js file by adding a useEffect hook where each change of route by the router will be tracked as a pageview

import { useEffect } from 'react'
import { useRouter } from 'next/router'
import * as gtag from '../lib/gtag'

const App = ({ Component, pageProps }) => {
  const router = useRouter()
  useEffect(() => {
    const handleRouteChange = (url) => {
    }'routeChangeComplete', handleRouteChange)
    return () => {'routeChangeComplete', handleRouteChange)
  }, [])

  return <Component {...pageProps} />

export default App

You are done! You should be able now to monitor your pages in Google Analytics.