Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 18, 2021 02:26 pm GMT

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

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

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.


Original Link: https://dev.to/theinfosecguy/5-steps-to-add-google-analytics-to-nextjs-application-3id9

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To