DEV Community

Cover image for 5 Steps to add Google Analytics to NextJS Application🙌
Keshav Malik
Keshav Malik

Posted on • Updated on

5 Steps to add Google Analytics to NextJS Application🙌

Hey Guys 👋👋

In this blog post, We'll be adding Google Analytics to our NextJS application.

I recently migrated my website Vulnerable.Livefrom CRA(Create React App) to NextJS and while integrating Google Analytics with NextJS Application I faced multiple issues so I decided to do a quick guide to add Google Analytics in NextJS.

How to add Google Analytics in NextJS Application?🔥

Step 1 - Starting with Google Analytics

Create a Google Analytics account and create a property. After creating property you will a Measurement ID.

Google Analytics Measurement ID

Step 2 - Creating Helper Functions

Now we have the Measurement ID, Let's start coding. Navigate to code editor and create a new folder lib and create a new file analytics.js and add the following code.

export const pageview = (url) => {
    if (window && window.gtag) {
        window.gtag('config', 'G-Y0*******', {
            page_path: url,
        })
    }
}

export const event = ({ action, params }) => {
    window.gtag('event', action, params)
}
Enter fullscreen mode Exit fullscreen mode

Replace G-Y0**** with your Measurement ID***

Step 3 - Adding GA to _app.js

Now it's time to add useEffect in our _app.js. You can find use below mentioned boilerplate code.

import Router from "next/router"
import { route } from 'next/dist/server/router';
import { useRouter } from 'next/router'
import { useEffect } from 'react';
import * as ga from '../lib/analytics'

function MyApp({ Component, pageProps }) {

  const router = useRouter()

  useEffect(() => {
    const handleRouteChange = (url) => {
      ga.pageview(url)
    }
    router.events.on('routeChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
    }
  }, [router.events])


  return (
      <Component
        {...pageProps}
        key={route}
      />
  )
}

export default MyApp

Enter fullscreen mode Exit fullscreen mode

Step 4 - Creating _document.js File

Now all we need to do is to edit our _document.js file. If you don't have one, all you need to is to create a _document.js file in the pages directory. You can use this below mentioned code as a boilerplate.

More about _document.js

Step 5 - Test the Code

We are done with everything. All you need to do is to deploy your code and check Google Analytics. Although it takes 24-48H for GA to populate data but you can navigate to Realtime tab and check users.😁🚀

Google Analytics

That's all for this post. Hope you guys liked it.

Top comments (3)

Collapse
 
rafde profile image
Rafael De Leon

Some comments may only be visible to logged-in visitors. Sign in to view all comments.