How to Add Google Analytics And Google AdSense To your Next JS Project!
Tags: analytics, webdev, nextjs, react
Published: 2021-12-24 12:50:17

## First create your next js app using `npm create-next-app app-name`
Then go to 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/apewbfmu9wy9bqzzay1o.png)

go to **github icon** and go to **examples**
in examples go to **with-google-analytics**
[Check Here](https://github.com/vercel/next.js/tree/canary/examples/with-google-analytics/lib)
here you go when you click on above link

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

![Starting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f26al50a5c0o5jmt6f4y.png)

**Created? Well Done!**
Now,
create a new file named as `gtag.js`
![gtag.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/60aulx9a9m8nckg7k0mi.png)

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,
  })
}
```
like this
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r3nn8baqjt4z8vwzm9az.png)

Now, How to get  **TrackingID**?
Just go to your 
[Google Analytics](https://analytics.google.com/)
 go  to the settings icon which means **admin**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gv3g3aktcd2zs469odt7.png)
 in that you will see
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i0ldvo2ge1p5qkl4ol04.png)

Go and click on **create Property** 
1.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7whlg74svv9qymwkkgwt.png)
 2.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j8mcmqst5j9w14uo7c9z.png)
 
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ay2kmj4ilaxv76mcytd2.png)
**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qtry5sorlkq0vvkqwov9.png)
Now go to pages folder in the github docs
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z219it6fgdl28pdvkabt.png)
 **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
```
 **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,
                });
              `,
                }}
            />

```

 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"/>
```
 Final code will be in _document.js file You can refer the main docs of [NEXTJs Custom Doc](https://nextjs.org/docs/advanced-features/custom-document)

```
<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>
```
Remember the whole code should be inside `<Head></Head>` Tag

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