DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for How to Add Google Analytics And Google AdSense To your Next JS Project!
Yash Kapure
Yash Kapure

Posted on • Updated on

How to Add Google Analytics And Google AdSense To your Next JS Project!

First create your next js app using npm create-next-app app-name

Then go to
Image description

go to github icon and go to examples
in examples go to with-google-analytics
Check Here
here you go when you click on above link

Go Back to Your Code editor create a new folder named lib

Starting

Created? Well Done!
Now,
create a new file named as gtag.js
gtag.js

and paste the following code over in gtag.js

Copy this Code

export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GA_ID

// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = (url) => {
  window.gtag('config', GA_TRACKING_ID, {
    page_path: url,
  })
}

// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }) => {
  window.gtag('event', action, {
    event_category: category,
    event_label: label,
    value: value,
  })
}
Enter fullscreen mode Exit fullscreen mode

like this
Image description

Now, How to get TrackingID?
Just go to your
Google Analytics
go to the settings icon which means admin
Image description
in that you will see
Image description

Go and click on create Property
1.
Image description
2.
Image description

Fill the required details such as website name and if you have your live website paste the link in the required section.

After that it will bring you to
Image description
Note: This Tracking ID is just for testing purpose You will find your Tracking Id on the same page

Copy Your Tracking ID and paste it
Image description
Now go to pages folder in the github docs
Image description
Copy all this code to_app.js

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

const 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 (
    <>
      {/* Global Site Tag (gtag.js) - Google Analytics */}
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
      />
      <Script
        id="gtag-init"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${gtag.GA_TRACKING_ID}', {
              page_path: window.location.pathname,
            });
          `,
        }}
      />
      <Component {...pageProps} />
    </>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

Last Step is to go to _document.js file where actual tracking will take place
If you don't find _document.js file. Then just go to pages folder and create a new file named as _document.js.
And add the following code over in the file.
This is for google analytics.

 <script async src={`https://www.googletagmanager.com/gtag/js?id=${process.env.GA_TRACKING_ID}`}></script>
<script
                dangerouslySetInnerHTML={{
                  __html: `
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
                gtag('config', '${process.env.GA_TRACKING_ID}', {
                  page_path: window.location.pathname,
                });
              `,
                }}
            />

Enter fullscreen mode Exit fullscreen mode

To add google adsense we just have to add 1 line.
for that follow the same steps create an account in google adsense
and get the script like this

 <script data-ad-client="ca-pub-xxxxx(yourid)" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"/>
Enter fullscreen mode Exit fullscreen mode

Final code will be in _document.js file You can refer the main docs of NEXTJs Custom Doc

<Head>
 <script data-ad-client="ca-pub-xxxxx(yourid)" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"/>
//##############
<script async src={`https://www.googletagmanager.com/gtag/js?id=${process.env.GA_TRACKING_ID}`}></script>
<script
                dangerouslySetInnerHTML={{
                  __html: `
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
                gtag('config', '${process.env.GA_TRACKING_ID}', {
                  page_path: window.location.pathname,
                });
              `,
                }}
            />
</Head>
Enter fullscreen mode Exit fullscreen mode

Remember the whole code should be inside <Head></Head> Tag

Hope this might help you.
Thanks for giving Your time to read this post!

Top comments (11)

 
yashkapure06 profile image
Yash Kapure

Okay so may be if you make separate component for ads and call it or import it on all the pages u want then it might work and i guess instead of keeping .jsx keep that adsence.jsx as adsence.js

 
yashkapure06 profile image
Yash Kapure

It's Alright, I have forked your project on github
I will definitely help you :)
My Github Profile check it out I have forked it

 
yashkapure06 profile image
Yash Kapure

Till when do u want
Bcz I have exams so
from Saturday I will start coding If u dont mind I would check it on saturday
:)

 
yashkapure06 profile image
Yash Kapure

I am unable to check due to invalid credentials Sorry!

Collapse
 
yashkapure06 profile image
Yash Kapure

Could u share github repo so that i could have a look?:)

Timeless DEV post...

How to write a kickass README

Arguably the single most important piece of documentation for any open source project is the README. A good README not only informs people what the project does and who it is for but also how they use and contribute to it.

If you write a README without sufficient explanation of what your project does or how people can use it then it pretty much defeats the purpose of being open source as other developers are less likely to engage with or contribute towards it.