How to Integrate Google Analytics and Adsense in a Next.js Project on Vercel

How to Integrate Google Analytics and Adsense in a Next.js Project on Vercel

When building a modern web application, tracking user behavior and monetizing content are crucial aspects. Google Analytics helps you understand your audience, while Google Adsense allows you to generate revenue through ads. Integrating these tools into a Next.js application hosted on Vercel is straightforward. This guide will walk you through the process step-by-step.

Prerequisites

Before you begin, ensure you have:

  • A Next.js project set up
  • A Google Analytics account with a tracking ID.
  • A Google Adsense account.

Step 1: Setting Up Google Analytics

  1. Create _document.tsx

First, create a _document.tsx file in the src/app directory if it doesn't already exist. This file allows you to customize the default HTML document structure in your Next.js application.

Add the following code to _document.tsx:

import { Html, Head, Main, NextScript } from 'next/document';

export default function Document() {

return (

{/* Google Analytics */}

async

src={`https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX`}

>

dangerouslySetInnerHTML={{

__html: `

window.dataLayer = window.dataLayer || [];

function gtag(){dataLayer.push(arguments);}

gtag('js', new Date());

gtag('config', 'G-XXXXXXXXXX', {

page_path: window.location.pathname,

});

`,

}}

/>

{/* Google Adsense */}

data-ad-client="ca-pub-XXXXXXXXXX"

async

src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"

>

);

}

In this example, replace G-XXXXXXXXXX with your actual Google Analytics tracking ID and ca-pub-XXXXXXXXXX with your Google Adsense client ID.

Google Analytics Script: This script initializes Google Analytics and configures it to track page views.

Google Adsense Script: This script loads Google Adsense to display ads on your site.

Additional Configuration

Make sure your Next.js application is deployed on Vercel.

Verify that your Google Analytics and Adsense accounts are correctly set up and linked to your website.

Conclusion

Integrating Google Analytics and Adsense into your Next.js project on Vercel is a straightforward process. By following these steps, you can start tracking user behavior and monetizing your content effectively. Happy coding!

Thank you for joining me on this coding journey. Happy developing!

Warm regards,

Naz

Affiliate Disclosure: This post may contain affiliate links. If you make a purchase through these links, I may earn a small commission at no additional cost to you. Thanks for supporting the blog!

Buy Me a Döner
Naz
Hi! I am Naz.

I am a software engineer and a mindfulness practitioner. I love to share my knowledge and experience with others. I am a lifelong learner and I am here to learn and grow with you.