Integrate-google-analytics-meta-ads

Integrate Google Analytics, Google Ads, WhatsApp Ads, and Facebook Meta Ads

March 4th, 2025

Step-by-Step Guide

Integrating advertising and analytics tools into a Next.js website allows you to track user behavior, optimize ad campaigns, and improve conversions. This guide covers how to integrate:

  1. Google Analytics
  2. Google Ads (Conversion Tracking & Remarketing)
  3. WhatsApp Ads (Tracking Conversions)
  4. Facebook (Meta) Ads (Pixel & Conversion API)

1. Google Analytics (GA4) Integration in Next.js App Router

Step 1: Create a Google Analytics Account

  1. Step 1: Get Google Analytics Measurement ID
  2. Go to Google Analytics.
  3. Set up a GA4 property and get your Measurement ID (
    G-XXXXXXXXXX
    ).

Step 2: Install Dependencies

pnpm add react-gtm-module

Step 3: Setup Google Tag Manager (GTM)

Create a GTM config file in lib/gtm.ts

import TagManager from "react-gtm-module";

export const initializeGTM = () => {
  TagManager.initialize({ gtmId: "GTM-XXXXXXX" });
};

**Step 4: Initialize GTM in **
layout.tsx

Modify 📌

app/layout.tsx
:

"use client";

import { useEffect } from "react";
import { initializeGTM } from "../lib/gtm";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    initializeGTM();
  }, []);

  return (
    <html lang="en">
      <head />
      <body>{children}</body>
    </html>
  );
}

Step 5: Configure Google Analytics in GTM

  1. Open Google Tag Manager.
  2. Create a New Tag → Select Google Analytics: GA4 Configuration.
  3. Add your Measurement ID (
    G-XXXXXXXXXX
    ).
  4. Set Trigger to All Pages.
  5. Publish the changes.

2. Google Ads (Conversion Tracking & Remarketing) Integration

Step 1: Get Google Ads Conversion ID

  1. Sign in to Google Ads.
  2. Get your Conversion ID (
    AW-XXXXXXXXX
    ).

Step 2: Add Google Ads Tracking Script

Modify 📌

app/layout.tsx
:

<Head>
  {/* Google Ads Conversion Tracking */}
  <script
    dangerouslySetInnerHTML={{
      __html: `
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('config', 'AW-XXXXXXXXX');
      `,
    }}
  />
</Head>

Replace

AW-XXXXXXXXX
with your Google Ads Conversion ID.

Step 3: Track Conversions on Button Click

Modify your button component 📌

components/BuyButton.tsx
:


3. Integrating WhatsApp Ads (Tracking Conversions)

"use client";

const handleGoogleAdsConversion = () => {
  if (typeof window !== "undefined") {
    window.gtag?.("event", "conversion", { send_to: "AW-XXXXXXXXX" });
  }
};

export const BuyButton = () => (
  <button onClick={handleGoogleAdsConversion}> Book A Call </button>
);

3. WhatsApp Ads Tracking Integration

Step 1: Get WhatsApp Pixel ID

  1. Open Meta Business Suite.
  2. Navigate to Events Manager and get the WhatsApp Pixel ID.

**Step 2: Add WhatsApp Pixel to **
layout.tsx

Modify 📌

app/layout.tsx
:

<Head>
  {/* WhatsApp Ads Pixel */}
  <script
    dangerouslySetInnerHTML={{
      __html: `
        !function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
        new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
        'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
        }(window,document,'script','dataLayer','GTM-XXXXXXXX');
      `,
    }}
  />
</Head>

Replace

GTM-XXXXXXXX
with your WhatsApp Pixel ID.

Step 3: Track WhatsApp Clicks

Modify 📌

components/WhatsAppButton.tsx
:

"use client";

const handleWhatsAppClick = () => {
  if (typeof window !== "undefined") {
    window.dataLayer?.push({ event: "whatsapp_click" });
  }
  window.location.href = "https://wa.me/91XXXXXXXXXX"; // Your WhatsApp number
};

export const WhatsAppButton = () => (
  <button onClick={handleWhatsAppClick}>Chat on WhatsApp</button>
);

4. Facebook (Meta) Ads Tracking Integration

Step 1: Get Facebook Pixel ID

  1. Open Meta Business Suite.
  2. Navigate to Events Manager and get your Facebook Pixel ID.

**Step 2: Add Facebook Pixel to **
layout.tsx

Modify 📌

app/layout.tsx
:

<Head>
  {/* Facebook Pixel */}
  <script
    dangerouslySetInnerHTML={{
      __html: `
        !function(f,b,e,v,n,t,s) {
          if(f.fbq) return; n=f.fbq=function(){n.callMethod ?
          n.callMethod.apply(n,arguments) : n.queue.push(arguments)};
          if(!f._fbq) f._fbq=n; n.push=n; n.loaded=true; n.version='2.0';
          n.queue=[]; t=b.createElement(e); t.async=true;
          t.src=v; s=b.getElementsByTagName(e)[0];
          s.parentNode.insertBefore(t,s);
        }(window, document,'script','https://connect.facebook.net/en_US/fbevents.js');

        fbq('init', 'XXXXXXXXXX');
        fbq('track', 'PageView');
      `,
    }}
  />
</Head>

Replace

XXXXXXXXXX
with your Facebook Pixel ID.

Step 3: Track Facebook Conversions on Button Click

Modify 📌

components/FacebookButton.tsx
:

"use client";

const handleFacebookConversion = () => {
  if (typeof window !== "undefined") {
    window.fbq?.("track", "Schedule Meeting", { value: 100, currency: "USD" });
  }
};

export const FacebookButton = () => (
  <button onClick={handleFacebookConversion}>Book A Call</button>
);

Server-Side Meta Conversion API

To send conversion events via Next.js API routes, create 📌

app/api/meta-conversion/route.ts
:

import { NextResponse } from "next/server";

export async function POST(req: Request) {
  const res = await fetch("https://graph.facebook.com/v12.0/PIXEL_ID/events", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      data: [
        {
          event_name: "Purchase",
          event_time: Math.floor(Date.now() / 1000),
          user_data: { client_ip_address: req.headers.get("x-forwarded-for") },
        },
      ],
      access_token: "YOUR_ACCESS_TOKEN",
    }),
  });

  return NextResponse.json({ success: true });
}

Now your Next.js App Router (

app/
** directory) with TypeScript** is fully set up for Google Analytics, Google Ads, WhatsApp Ads, and Facebook Meta Ads.

Final Checklist

Google Analytics (GA4) via GTM → Tracks page views
Google Ads Tracking → Tracks conversions
WhatsApp Ads Tracking → Tracks WhatsApp button clicks
Facebook Meta Ads Tracking → Tracks Buttons

Version : 1.0.3

Ready to work with us?

We’re here to help you solve your problems!

Suntec Singapore

17-136, Suntec Tower 5, 5 Temasek Blvd, Singapore 038985

+65 89520271

Times Square Hinjewadi

304, Level 3, Times Square, Hinjawadi Pune, Maharashtra 411057, India

+91 8360007575