the-geeky-codes-high-resolution-logo-color-on-transparent-background geeky code red logo
  • Home
  • AI
    AIShow More
    generate vector icons
    Generate Vector Icons with ChatGPT DALLE 3: A Comprehensive Guide
    14 Min Read
    Dalle 3
    Dalle 3: A Step-by-Step Guide to Mastering AI Art Generation
    4 Min Read
    5 Best AI Tools to Convert Images to Video Animations
    5 Best AI Tools to Convert Images to Video Animations
    8 Min Read
    Exploring the Impressive Mistral 7B Model
    Exploring the Impressive Mistral 7B Model for Text Summarization and Coding
    6 Min Read
    The AI Revolution this week
    Must Read – The AI Revolution this week 30 Sep 2023: Integrating AI Tools into Everyday Life
    6 Min Read
  • Tutorial
    • React js
    • Python
    • Javascript
  • AI Tools
Reading: How to Install Google Analytics 4 in Next.js 15 (App Router) with TypeScript [2024]
Share
the geeky codesthe geeky codes
Aa
  • AI
  • AI Tools
  • Javascript
  • Python
  • React js
  • Advertise
Search
  • Categories
    • AI
    • AI Tools
    • Javascript
    • Python
    • React js
  • More
    • Advertise
Follow US
Copyright ©2023 The Geeky codes. All Rights Reserved.
the geeky codes > Blog > Tutorial > Nextjs > How to Install Google Analytics 4 in Next.js 15 (App Router) with TypeScript [2024]
TutorialNextjs

How to Install Google Analytics 4 in Next.js 15 (App Router) with TypeScript [2024]

thegeekycodes By thegeekycodes 20 November 2024 6 Min Read
Google Analytics 4 in Nextjs 14
SHARE

In this comprehensive guide, you’ll learn how to integrate Google Analytics 4 (GA4) into your Next.js 14 application using the App Router and TypeScript. We’ll cover everything from basic setup to advanced tracking configurations, ensuring you get accurate analytics while maintaining optimal performance.

Contents
Why GA4 in Next.js?PrerequisitesStep-by-Step Installation1. Set Up the Google Analytics Account2. Project Configuration3. Environment Setup4. TypeScript Configuration5. Analytics Utilities6. Analytics Component7. Root Layout Integration8. Custom Event TrackingTesting & VerificationAdvanced ConfigurationContent Security PolicyPrivacy ComplianceTroubleshootingBest PracticesAdditional ResourcesConclusion

Why GA4 in Next.js?

  • Real-time user behavior tracking
  • Enhanced performance with proper script loading
  • TypeScript support for better development
  • Built-in SEO optimization
  • Privacy compliance (GDPR, CCPA)

Prerequisites

Before starting, ensure you have:

  1. Next.js 14 or later installed
  2. Node.js version 18.17 or higher
  3. TypeScript configured
  4. Google Analytics 4 account
  5. Basic familiarity with App Router

Step-by-Step Installation

1. Set Up the Google Analytics Account

  1. Visit Google Analytics
  2. Create a new property or select existing one
  3. Set up a web data stream
  4. Copy your Measurement ID (G-XXXXXXXXXX)

2. Project Configuration

First, create a new Next.js project if you haven’t already:

npx create-next-app@latest my-analytics-app
cd my-analytics-app

3. Environment Setup

Create .env.local in your project root:

NEXT_PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXXXX

4. TypeScript Configuration

Create types/google-analytics.d.ts:

interface Window {
  gtag: (
    command: string,
    targetId: string,
    config?: {
      page_path?: string;
      page_location?: string;
      page_title?: string;
      [key: string]: any;
    }
  ) => void;
}

5. Analytics Utilities

Create utils/analytics.ts:

export const GA_MEASUREMENT_ID = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID;

// Enhanced pageview tracking
export const pageview = (url: string, title: string) => {
  if (typeof window.gtag !== 'undefined') {
    window.gtag('config', GA_MEASUREMENT_ID!, {
      page_path: url,
      page_title: title,
      page_location: window.location.href,
      send_page_view: true
    });
  }
};

// Advanced event tracking
export const event = ({
  action,
  category,
  label,
  value,
}: {
  action: string;
  category: string;
  label: string;
  value?: number;
}) => {
  if (typeof window.gtag !== 'undefined') {
    window.gtag('event', action, {
      event_category: category,
      event_label: label,
      value: value,
      non_interaction: false,
      timestamp: new Date().toISOString()
    });
  }
};

6. Analytics Component

Create components/GoogleAnalytics.tsx:

'use client';

import Script from 'next/script';
import { usePathname, useSearchParams } from 'next/navigation';
import { useEffect } from 'react';
import { pageview } from '@/utils/analytics';

const GoogleAnalytics = () => {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    const url = pathname + searchParams.toString();

    // Delayed tracking for accurate title
    setTimeout(() => {
      pageview(url, document.title);
    }, 100);
  }, [pathname, searchParams]);

  return (
    <>
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID}`}
        onLoad={() => {
          console.log('Google Analytics loaded successfully');
        }}
        onError={(e) => {
          console.error('Google Analytics failed to load:', e);
        }}
      />
      <Script
        id="google-analytics"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID}', {
              page_path: window.location.pathname,
              cookie_flags: 'SameSite=None;Secure',
              cookie_domain: window.location.hostname,
              send_page_view: true
            });
          `,
        }}
      />
    </>
  );
};

export default GoogleAnalytics;

7. Root Layout Integration

Update app/layout.tsx:

import { Metadata } from 'next';
import GoogleAnalytics from '@/components/GoogleAnalytics';

export const metadata: Metadata = {
  title: 'Your App Name',
  description: 'Your app description for better SEO',
  keywords: ['Next.js', 'Google Analytics', 'TypeScript', 'App Router'],
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <head>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
      </head>
      <body>
        {process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID && (
          <GoogleAnalytics />
        )}
        {children}
      </body>
    </html>
  );
}

8. Custom Event Tracking

Example usage in any component:

import { event } from '@/utils/analytics';

export default function FeatureComponent() {
  const handleClick = () => {
    event({
      action: 'feature_click',
      category: 'engagement',
      label: 'premium_feature',
      value: 1
    });
  };

  return (
    <button onClick={handleClick}>
      Premium Feature
    </button>
  );
}

Testing & Verification

  1. Build your application:
npm run build
npm start
  1. Open Google Analytics Real-Time view
  2. Navigate through your website
  3. Verify pageviews and events are tracking

Advanced Configuration

Content Security Policy

Update next.config.js:

const nextConfig = {
  async headers() {
    return [
      {
        source: '/:path*',
        headers: [
          {
            key: 'Content-Security-Policy',
            value: `
              script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.googletagmanager.com https://www.google-analytics.com;
              img-src 'self' https://www.google-analytics.com;
              connect-src 'self' https://www.google-analytics.com;
            `.replace(/\s+/g, ' ').trim()
          }
        ]
      }
    ];
  }
};

export default nextConfig;

Privacy Compliance

  1. Add Cookie Consent:
const hasConsent = () => {
  // Implement your consent check logic
  return localStorage.getItem('analytics-consent') === 'true';
};

// Only load GA if consent is given
{hasConsent() && <GoogleAnalytics />}
  1. Update Privacy Policy
  2. Implement Data Anonymization
  3. Add Cookie Banner

Troubleshooting

Common issues and solutions:

  1. Analytics Not Loading
  • Check browser console for errors
  • Verify Measurement ID
  • Check CSP headers
  1. Missing Page Views
  • Confirm script loading order
  • Check route change handlers
  • Verify consent management
  1. TypeScript Errors
  • Update type definitions
  • Check import paths
  • Verify tsconfig settings

Best Practices

  1. Performance
  • Use strategy="afterInteractive"
  • Implement lazy loading
  • Optimize tracking code
  1. Error Handling
  • Add Script onError handlers
  • Implement fallbacks
  • Log tracking failures
  1. Maintenance
  • Regular version updates
  • Monitor analytics health
  • Audit tracking events

Additional Resources

  • Next.js Documentation
  • GA4 Documentation
  • TypeScript Handbook
  • React Documentation

Conclusion

You now have a production-ready Google Analytics 4 implementation in your Next.js application. This setup provides accurate tracking while maintaining performance and privacy compliance.


Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Twitter Copy Link Print
Previous Article docker compose Getting Started with Docker Compose
Next Article Generate-Dynamic-OpenGraph-Images-in-Nextjs15 How to Generate Dynamic OpenGraph Images in Next.js App Router 15 with TypeScript
Leave a comment

Leave a Reply Cancel reply

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

Twitter Follow
Telegram Follow

Subscribe Now

Subscribe to our newsletter to get our newest articles instantly!

Most Popular
Advanced Routing Techniques in Nextjs 15
Advanced Routing Techniques in Next js 15
20 November 2024
Attachment Details Image-to-Text-Converter-with-Claude-Nextjs-15
Building an AI-Powered Image-to-Text Converter with Claude, Next.js 15, and Vercel AI SDK
20 November 2024
Generate-Dynamic-OpenGraph-Images-in-Nextjs15
How to Generate Dynamic OpenGraph Images in Next.js App Router 15 with TypeScript
20 November 2024
docker compose
Getting Started with Docker Compose
20 November 2024
Image Processing with OpenCV in Python
Image Processing with OpenCV in Python
19 July 2024

You Might Also Like

Advanced Routing Techniques in Nextjs 15
TutorialNextjs

Advanced Routing Techniques in Next js 15

7 Min Read
Attachment Details Image-to-Text-Converter-with-Claude-Nextjs-15
TutorialNextjs

Building an AI-Powered Image-to-Text Converter with Claude, Next.js 15, and Vercel AI SDK

4 Min Read
Generate-Dynamic-OpenGraph-Images-in-Nextjs15
TutorialNextjs

How to Generate Dynamic OpenGraph Images in Next.js App Router 15 with TypeScript

9 Min Read
docker compose
TutorialDocker

Getting Started with Docker Compose

6 Min Read

Always Stay Up to Date

Subscribe to our newsletter to get our newest articles instantly!

the geeky codes geeky code red logo

Providing valuable resources for developers in the form of code snippets, software tutorials, and AI related content.

About

  • About Us
  • Contact
  • Terms and Conditions
  • Privacy Policy
  • Disclaimer
  • Affiliate Disclosure

Resource

  • The Art of AI Prompt Engineering: Crafting Effective Inputs for AI Models

Get the Top 10 in Search!

Looking for a trustworthy service to optimize the company website?
Request a Quote
© 2023 The Geeky Codes. All Rights Reserved
We are happy to see you join Us!

🔥📢Subscribe to our newsletter and never miss our latest code snippets, tutorials and AI updates

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?