How to setup Google Adsense and Analytics in Next Js app

Setting up Google Analytics and Adsense with Next Js is not much of a big deal, but doing it correctly is super essential. Today, I am going to share how you can set up those both just in some seconds.

I believe you’ve already created your Next Js app, and you want to install Google Adsense and Analytics in your already developed project. So, I’ll be beginning the method from a fresh new Next Js project.

Google Adsense and Analytics in Next Js

Setting up the project (Optional)

First of I’ll be creating a new Next Js project with npx [email protected] to teach you well. Our initial project would look something similar to this.

├── next.config.js
├── node_modules
├── package.json
├── pages
│   ├── api
│   │   └── hello.js
│   ├── _app.js
│   └── index.js
├── public
│   ├── favicon.ico
│   └── vercel.svg
├── README.md
├── styles
│   ├── globals.css
│   └── Home.module.css
└── yarn.lock

Creating a new parent layout

I love to create an independent parent layout that contains all the essentials like meta, custom scripts and stuff. So, let’s do it.

First, you need to create a directory called layout/ inside the project.

mkdir layout
cd layout

Now, inside the layout/ directory, create a file named Layout.jsx (or .tsx if you’re using TypeScript).

touch Layout.jsx

Now, it’s time to structure, code and inserts the Google Adsense and Analytics scripts.

Structuring Layout.jsx

We will be giving two parameters in Layout() component; children and title. The children parameter is extremely essential, but if you want title to be static, then you can replace/remove it accordingly.

Our Layout would look something like this:

Here’s the code:


import React from 'react';
import Head from "next/head";

function Layout({children, title="Next JS App"}) {
    return (
        <div>
            {/* Google Adsense */}
            {/* Google Analytics */}
            <Head>
                <link rel="shortcut icon" href={"/static/favicon.svg"}/>
                <meta name="robots" content="index, follow"/>
                <meta httpEquiv="Content-Type" content="text/html; charset=utf-8"/>
                <meta name="language" content="English"/>
                <meta name="author" content="Author Name"/>
                <title>{title}</title>
            </Head>
            {children}
        </div>
    );
}

export default Layout;

Inserting scripts

Now, we are going to insert Analytics and Adsense codes. We will be using Next Js’ afterInteractive feature for this task, which allows us to make the initial loading of our pages fast.

afterInteractive makes Google Adsense or Analytics load after the main page content has finished loading or when the user scrolls down to the part of the page where they are included. This makes our app efficient and fast to load.

Import Next Js Script

Before inserting Adsense and Analytics script, you should import Script tag of Next Js.

import Script from "next/script";

Inserting Google Adsense in Next Js

Finally, you can insert your Google Adsense code in Next Js like the following:

<Script data-ad-client="ca-pub-YX_CA_PUB_NUM_XY" async
     src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></Script>

Insert the upper code outside the <Head> tag of Next Js, because the Script gets executed after the loading of the page and automatically gets inserted inside the HTML.
[MUST REQUIRED]

Replace YX_CA_PUB_NUM_XY with your ca-pub code. And you’re extremely close to finishing the whole task.

Inserting Google Analytics in Next Js

Now, I will show you how you can use Google Analytics tags with afterInteractive strategy.

Your Google Analytics code can be inserted into your Next Js app like the following:

<Script strategy={"afterInteractive"} src={`https://www.googletagmanager.com/gtag/js?id=G-MQMPTMDET6`}/>
<Script id={"google-analytics"} strategy={"afterInteractive"} dangerouslySetInnerHTML={{
    __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
        
            gtag('config', 'G-MQMPTMDET6');
        `
}}/>

Replace YX_GACODE_XY with your google-analytics-ua code. Looks something like this: 123456789-1

And you’re about to be done.

Layout Code Result

Our Layout.jsx code would look something like this:


import React from 'react';
import Head from "next/head";
import Script from "next/script";

function Layout({children, title="Next JS App"}) {
    return (
        <div>
            <Script strategy={"afterInteractive"} src={`https://www.googletagmanager.com/gtag/js?id=G-MQMPTMDET6`}/>
            <Script id={"google-analytics"} strategy={"afterInteractive"} dangerouslySetInnerHTML={{
                __html: `
                        window.dataLayer = window.dataLayer || [];
                        function gtag(){dataLayer.push(arguments);}
                        gtag('js', new Date());
                    
                        gtag('config', 'G-MQMPTMDET6');
                    `
            }}/>
            <Script data-ad-client="ca-pub-YX_CA_PUB_NUM_XY" async
                    src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></Script>
            <Head>
                <link rel="shortcut icon" href={"/static/favicon.svg"}/>
                <meta name="robots" content="index, follow"/>
                <meta httpEquiv="Content-Type" content="text/html; charset=utf-8"/>
                <meta name="language" content="English"/>
                <meta name="author" content="Author Name"/>
                <title>{title}</title>
            </Head>
            {children}
        </div>
    );
}

export default Layout;

Using the Layout

After doing all those setups, if you don’t use the Layout, it won’t work. So, to use it, we will be importing the Layout inside our _app.js and using it to wrap up our main app.

Go to pages/_app.js (or _app.tsx if you use TypeScript) and then import Layout there.

import Layout from "../layout/Layout";

After importing it, use it to wrap <Component {...pageProps} />. It would look something like the below.

import '../styles/globals.css'
import Layout from "../layout/Layout";

function MyApp({ Component, pageProps }) {
  return <Layout>
    <Component {...pageProps} />
  </Layout>
}

export default MyApp

Finally, our app is ready to serve Google Adsense Ads and track users’ data with Google Analytics.

I hope this article helped you.

Have a good day!

Posted by Bishwas Bhandari

I am 18 years, young developer. Trying to simplify the problems of the people who are struggling around the web to provide something better in this world. I have developed Adsense Eligibility Checker Tool to help you guys to check whether your site is eligible or worthy for Google Adsense.

One thought on “How to setup Google Adsense and Analytics in Next Js app”

Leave a Reply

Your email address will not be published. Required fields are marked *